How to remove certain characters from a string in C++?



In this section, we will see how to remove some characters from a string in C++. In C++ we can do this task very easily using erase() and remove() function. The remove function takes the starting and ending address of the string, and a character that will be removed.

// Input String = "Hello TutorialsPoint" Char = 'o' // Output String = "Hell TutrialsPint"

Algorithm to Remove Certain Characters from a String

Here is the algorithm to remove certain characters from a string in C++:

Step 1: Take a string and a character to be removed as input.
Step 2: Define erase function that takes remove function and the character as arguments.
Step 3: Use the arguments of remove function to define the range of characters to be removed. (i.e., starting and ending address of the string)
Step 4: Call the erase function to remove the character from the string.
Step 5: Print the result.
Step 6: End

Example Code to Remove Certain Characters from a String

In this example, we will remove the character 'a' from the string "apple banana".

Open Compiler
#include <iostream> #include <string> #include <algorithm> using namespace std; int main() { string str = "apple banana"; char charToRemove = 'a'; // Remove the character from the string str.erase(remove(str.begin(), str.end(), charToRemove), str.end()); cout << "Final string: " << str << endl; return 0; }

The output of the above code will be:

Initial string: apple banana
Final string: pple bnn
Farhan Muhamed
Farhan Muhamed

No Code Developer, Vibe Coder

Updated on: 2025-06-09T19:09:19+05:30

87K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements