C Program to Remove all Occurences of a Character from a String

Here we’ll see how to remove all occurences of a character from a string. For example, if we remove the character ‘o‘ from the string “The quick brown fox jumps over the lazy dog“, the result will be “The quick brwn fx jumps ver the lazy dg“. All four occurneces of ‘o’ removed from the string. The other characters will fill the holes created by removal of ‘o’.

Here is the C program.

#include <stdio.h>

void remove_char(char* str, char ch){
  int i = 0, count = 0;
  
  while (str[i + count] != '\0') {
    /*Skipping the matched character...*/
    if (str[i + count] == ch) count++;
    
    str[i] = str[i + count];
    i++;
  }
  str[i] = '\0';
}

int main() {
  char str[256], ch;
  printf("Enter a string: ");
  fgets(str, sizeof(str), stdin);
  printf("Enter a character to remove: ");
  ch = getchar();
  
  remove_char(str, ch);
  printf("The string after removing %c: %s\n", ch, str);
  return 0;
}

The above program takes a string and a character as input. Then it call the remove_char() function to remove the character and prints after removal.

Here is the output.

remove all occurences of a character from a string

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0