/* C Program to Remove All Occurrences of a Character in a String */

#include <stdio.h>

#include <string.h>

int main()

{

char str[100], ch; 

int i, len, j; 



printf("\n Please Enter any String :  "); 

gets(str); 

 

printf("\n Please Enter the Character that you want to Remove :  "); 

scanf("%c", &ch); 

 

len = strlen(str); 

   	 

for(i = 0; i < len; i++) 

{ 

	if(str[i] == ch) 

	{ 

		for(j = i; j < len; j++) 

		{ 

			str[j] = str[j + 1]; 

		} 

		len--; 

		i--;	 

	}  

}	 

printf("\n The Final String after Removing All Occurrences of '%c' = %s ", ch, str); 

 

return 0; 

}

can anyone explain this code

You are first running the for loop, whenever you encounter a character that needs to be removed, you go into the inner for loop, while skipping that character, and copies the entire string to itself, and then do len–(length decereased due to removal of a character) and
i–(to make sure the index doesnt overrun the length of the array). Do you know vectors? I have a much simpler approach. Also, your the time complexity of this code is O(n^2), which is not very good. Even without a vector, just make another string array, and keep copying them, until you find the wrong character, when such a character is found, just skip it!

1 Like

Thanks

No, I haven’t studied vectors yet