Basic

Switch Case

Goto

Operators

if Statement

Nested if

While Loop

For Loop

Patterns

Array

2D Array

String Function Example

Pointers

Recursion Function

Structure

Excersises

Others


C Program to Remove All Occurrences of a Character in a String


Write a to C program to remove all occurrences of a character in a given string.

  • Reads a string character by character until a newline is encountered and stores it in an array.
  • Prompts the user to enter a character that should be removed from the string.
  • Traverses the string, copying only characters that are not equal to the one specified into a new position.
  • Ends the modified string properly and prints the updated version without the specified character.
Example : pgm.c
#include <stdio.h>

int main() {
    char str[200], ch;
    int i = 0, j = 0;

    printf("Enter a string: ");
    while ((str[i] = getchar()) != '\n') {
        i++;
    }
    str[i] = '\0';

    printf("Enter the character to remove: ");
    scanf(" %c", &ch); // space before %c to consume leftover newline

    // Remove the character
    i = 0;
    while (str[i] != '\0') {
        if (str[i] != ch) {
            str[j++] = str[i];
        }
        i++;
    }
    str[j] = '\0';

    printf("Updated string: %s\n", str);

    return 0;
}

Output :

Enter a string: programming
Enter the character to remove: g
Updated string: proramin