How to remove punctuation from a string in C

I am looking to remove all punctuation from a string and make all lowercase letters lowercase in C, any suggestions?

+3
source share
4 answers

Just a sketch of the algorithm using the functions provided by ctype.h:

#include <ctype.h>

void remove_punct_and_make_lower_case(char *p)
{
    char *src = p, *dst = p;

    while (*src)
    {
       if (ispunct((unsigned char)*src))
       {
          /* Skip this character */
          src++;
       }
       else if (isupper((unsigned char)*src))
       {
          /* Make it lowercase */
          *dst++ = tolower((unsigned char)*src);
          src++;
       }
       else if (src == dst)
       {
          /* Increment both pointers without copying */
          src++;
          dst++;
       }
       else
       {
          /* Copy character */
          *dst++ = *src++;
       }
    }

    *dst = 0;
}

Standard reservations apply: Completely untested; refinements and optimizations are left as an exercise for the reader.

+10
source

Iterate over the characters of a string. Whenever you encounter punctuation ( ispunct), do not copy it to the output string. Whenever you encounter "alpha char" ( isalpha), use tolowerto convert it to lowercase.

<ctype.h>

( ), . .

+12

C , , , : .

#include <ctype.h>

void reformat_string(char *src, char *dst) {
    for (; *src; ++src)
        if (!ispunct((unsigned char) *src))
            *dst++ = tolower((unsigned char) *src);
    *dst = 0;
}

src dst , .

, tolower(*src++), tolower .

, ( strchr ), .

+5

:

void strip_punct(char * str) {
    int i = 0;
    int p = 0;
    int len = strlen(str);
    for (i = 0; i < len; i++) {
        if (! ispunct(str[i]) {
            str[p] = tolower(str[i]);
            p++;
        }
    }
}
0

Source: https://habr.com/ru/post/1724652/


All Articles