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

后端 未结 7 606
有刺的猬
有刺的猬 2020-11-30 11:24

I\'m attempting to remove a character from a string in C. The problem I am having with my code is that it removes the first instance of the character from the string but als

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 11:37

    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.

提交回复
热议问题