Example:
Input string : I Love Programming. I Love CodeForWin.
Input character to remove : 'I'
Output : Love Programming. Love CodeForWin.
Required knowledge
Basic C programming, If else, Loop, Array, String, FunctionsProgram to remove all occurrences of a character from string
/** * C program to remove all occurrences of a character from the given string. */ #include <stdio.h> #include <string.h> #define MAX_SIZE 100 //Maximum size of the string /** Function declaration */ void removeAll(char *, const char); int main() { char string[MAX_SIZE]; char toRemove; printf("Enter any string: "); gets(string); printf("Enter character to remove from string: "); toRemove = getchar(); removeAll(string, toRemove); printf("String after removing '%c': %s\n", toRemove, string); return 0; } /** * Function to remove all occurrences of a character from the string. */ void removeAll(char * string, const char toRemove) { int i, j; int len = strlen(string); for(i=0; i<len; i++) { /* * If the character to remove is found then shift all characters to one * place left and decrement the length of string by 1. */ if(string[i] == toRemove) { for(j=i; j<len-1; j++) { string[j] = string[j+1]; } len--; string[len] = '\0'; // If a character is removed then make sure i doesn't increments i--; } } }
Output
Enter any string: I Love Programming. I Love CodeForWin.
Enter character to remove from string: I
String after removing 'I': Love Programming. Love CodeForWin.
Enter character to remove from string: I
String after removing 'I': Love Programming. Love CodeForWin.
Happy coding ;)
You may also like
- String programming exercises index.
- C program to find first occurrence of a given character in string.
- C program to remove first occurrence of a character from the string.
- C program to remove last occurrence of a character from the string.
- C program to find first occurrence of a given word in string.
- C program to count frequency of each character in a string.
- C program to concatenate two strings.
- C program to count total number of words in a string.
- C program to find reverse of a String.
- C program to check whether a string is palindrome or not.