Removing digits and all punctuation except apostrophe from a string in C

You are confusing strings and characters. A character literal is enclosed in '. A string literal is enclosed in " and is an array of characters.

e.g.:

"This is a string literal"
'c' // this is character

To test if a char is not z for instance, you write:

char c = ...;    
if (c == 'z')

For special characters, like ', new line, tab etc. you have to escape them like this:

char c1 = '\'' // this is a ' character
char c2 = '\t' // this is a tab character

strcpm is for comparing strings. If you want to compare characters, == are what you need, as I’ve shown above.


Your function can be written simply as this:

int strip(char* str)
{
    int from, to;       
    for (from = 0, to = 0; str[from] != '\0'; ++from) {
        if (!isdigit(str[from]) && (!ispunct(str[from]) || str[from] == '\'')) {
            str[to] = tolower(str[from]);
            ++to;
        }
    }
    str[to] = '\0';
}

example input and output:

int main(void)
{
    char str[] = "This is 'Sparta'! The 200. I ,think,";
    strip(str);
    printf("%s\n", str);
    return 0;
}

output:

this is 'sparta' the  i think

Browse More Popular Posts

Leave a Comment