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.

Required knowledge

Basic C programming, C for loop, Array, functions, Strings

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++;
    }
}



Output:

Enter any string: c programm
Enter character to remove from string: m
String after removing first 'm' : c program
Process returned 0 (0x0) execution time : 11.984 s



Instagram