C++ Program to Remove All Occurrences of a Character From a String

1. Introduction

String manipulation is one of the most frequently encountered tasks in programming. One such task is removing all occurrences of a specific character from a string. In this blog post, we will walk you through a simple C++ program that accomplishes this.

2. Program Overview

Our program will:

1. Prompt the user to enter a string.

2. Ask the user for the character they wish to remove from the entered string.

3. Implement a function to remove all occurrences of the specified character.

4. Display the modified string.

3. Code Program

#include<iostream>
#include<string>
using namespace std;

// Function to remove all occurrences of 'charToRemove' from 'str'
string removeCharacter(const string& str, char charToRemove) {
    string result = "";  // To store the result string without 'charToRemove'

    // Traverse the original string
    for (char ch : str) {
        // If current character is not the one to remove, add to the result
        if (ch != charToRemove) {
            result += ch;
        }
    }

    return result;
}

int main() {
    string inputStr;
    char charToRemove;

    // Take input from the user
    cout << "Enter the string: ";
    getline(cin, inputStr);
    cout << "Enter the character to remove: ";
    cin >> charToRemove;

    // Call the function and display the result
    string modifiedStr = removeCharacter(inputStr, charToRemove);
    cout << "Modified string: " << modifiedStr << endl;

    return 0;
}

Output:

Enter the string: programming is fun
Enter the character to remove: m
Modified string: prograing is fun

4. Step By Step Explanation

1. The user enters a string and specifies a character they wish to remove from that string.

2. The removeCharacter function is designed to handle the removal process. It creates a new string called result.

3. As the function traverses the original string, if the current character is not the one we wish to remove, it's added to the result string.

4. Finally, the result string, which does not contain any instances of the character to be removed, is returned.

5. In the main function, we then display the modified string to the user.

Comments