Write a C program to remove all occurrences of a given character from the string using loop. Write a function to remove all occurrences of a character from a string. How to remove all occurrences of a character from the string in C programming. Logic to remove all occurrences of a character from a given string in C program.
Example
Input
Input string : I Love Programming. I Love Codeforwin. Input character to remove : 'I'
Output
String after removing all 'I' : Love Programming. Love Codeforwin.
Required knowledge
Basic C programming, If else, For loop, Array, String, Functions
Must know –
Logic to remove all occurrences of a character
Before you learn how to remove all occurrences of a character, you might like to check
Read more –
Below is the step by step descriptive logic to remove all occurrences of a character in given string.
- Input string from user, store in some variable say str.
- Input character to remove from user, store it in some variable say toRemove.
- Run a loop from start character of str to end.
- Inside the loop, check if current character of string str is equal to toRemove. If the mentioned condition is true then shift all character to one position left from current matched position to end of string.
Program 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 string size
/** Function declaration */
void removeAll(char *, const char);
int main()
{
char str[MAX_SIZE];
char toRemove;
printf("Enter any string: ");
gets(str);
printf("Enter character to remove from string: ");
toRemove = getchar();
removeAll(str, toRemove);
printf("String after removing '%c': %s", toRemove, str);
return 0;
}
/**
* Function to remove all occurrences of a character from the string.
*/
void removeAll(char * str, const char toRemove)
{
int i, j;
int len = strlen(str);
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(str[i] == toRemove)
{
for(j=i; j<len; j++)
{
str[j] = str[j+1];
}
len--;
// 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.
Happy coding 😉
Recommended posts
- String programming exercises index.
- C program to find first occurrence of a given character in string.
- C program to find first occurrence of a given word in string.
- C program to replace first occurrence of a character with another in string.
- C program to replace last occurrence of a character with another in string.
- C program to replace all occurrences of a character with another in string.
- C program to count frequency of each character in a string.