C program to remove all occurrences of a character from string

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.

  1. Input string from user, store in some variable say str.
  2. Input character to remove from user, store it in some variable say toRemove.
  3. Run a loop from start character of str to end.
  4. 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 😉