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

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
  
void remove_all_occurrences(char *s, const char ch) {
    int len = strlen(s);
 
    for (int i = 0; i < len; i++) {
        if (s[i] == ch) {
            for (int j = i; j < len; j++) {
                s[j] = s[j + 1];
            }
            len--;
            i--;
        }
    }
}


int main() {
    char s[] = "c c++ c# java php python rust";
  
    remove_all_occurrences(s, 'p');
    puts(s);
     
    remove_all_occurrences(s, 'x');
    puts(s);
     
    remove_all_occurrences(s, 'c');
    puts(s);  
       
    return 0;
}

    
         
/*
run:
      
c c++ c# java h ython rust
c c++ c# java h ython rust
 ++ # java h ython rust
   
*/

 



answered Apr 1, 2019 by avibootz
edited Oct 12, 2024 by avibootz

Related questions

3 answers 173 views
1 answer 141 views
1 answer 111 views
1 answer 118 views
1 answer 132 views
...