C program to remove all occurrences of a character from the 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.

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, Functions

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 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.

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment