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.

Required knowledge

Basic C programming, C if-else, C for loop, Array, functions, Strings

Logic to remove all occurrences of a character

Before you learn how to remove all occurrences of a character, you might like to check

Write a C program to remove first occurrence of a character from string.
Write a C program to remove last occurrence of a character from string.

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: c programcoding
Enter character to remove from string: o
String after removing 'o': c prgramcding
Process returned 0 (0x0) execution time : 21.216 s



Instagram