C program to remove first occurrence of a character from string

Write a C program to read any string from user and remove first occurrence of a given character from the string. The program should also use the concept of functions to remove the given character from string. How to remove first occurrences of a given character from the string.

Example :
Input string: I Love programming. I Love CodeForWin. I Love India.
Input character to remove: 'I'
Output: Love Programming. I Love CodeForWin. I Love India.

Required knowledge

Basic C programming, If else, Loop, Array, String, Functions

Program to remove first occurrence of character

/**
 * C program to remove first occurrence 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 removeFirst(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();

    removeFirst(string, toRemove);

    printf("\nOutput : %s", string);

    return 0;
}



/**
 * Function to remove first occurrence of a character from the string.
 */
void removeFirst(char * string, const char toRemove)
{
    int i;
    int len = strlen(string);

    i=0;

    /* Run loop until the first occurrence of the character is not found */
    while(i<len && string[i]!=toRemove)
        i++;

    /*
     * Shift all characters right to the position found above to one place left
     */
    while(i<len-1)
    {
        string[i] = string[i+1];
        i++;
    }

    /* Make the last character null */
    string[i] = '\0';
} 


Output
Enter any string: I Love programming. I Love CodeForWin. I Love India.
Enter character to remove from string: I

Output : Love programming. I Love CodeForWin. I Love India.

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