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

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

Must know – Program to find first occurrence of a character in a given string

Logic to remove first occurrence of a character in string

Below is the step by step descriptive logic to remove first occurrence of a character in a given string.

  1. Input string from user, store it in some variable say str.
  2. Input character to remove from user, store it in some variable say toRemove.
  3. Find first occurrence of the given character toRemove in str.
  4. From the first occurrence of given character in string, shift next characters one place to its left.

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 string size

/* Function declaration */
void removeFirst(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();

    removeFirst(str, toRemove);

    printf("String after removing first '%c' : %s", toRemove, str);

    return 0;
}


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

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

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

Read more – Program to remove last occurrence of a character from string

Output

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

String after removing first 'I' : Love programming. I Love Codeforwin. I Love India.

Happy coding 😉