How to remove all occurrences of a given character from string in C?

You can do it like this:

void remove_all_chars(char* str, char c) {
    char *pr = str, *pw = str;
    while (*pr) {
        *pw = *pr++;
        pw += (*pw != c);
    }
    *pw = '\0';
}

int main() {
    char str[] = "llHello, world!ll";
    remove_all_chars(str, 'l');
    printf("'%s'\n", str);
    return 0;
}

The idea is to keep a separate read and write pointers (pr for reading and pw for writing), always advance the reading pointer, and advance the writing pointer only when it’s not pointing to a given character.

Leave a Comment