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

C++Server Side ProgrammingProgramming

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: A number string “ABAABACCABA”
Output: “BBCCB”


Step 1:Take a string
Step 2: Remove each occurrence of a specific character using remove() function
Step 3: Print the result.
Step 4: End

Example Code

 Live Demo


using namespace std;
main() {
   string my_str = "ABAABACCABA";

   cout << "Initial string: " << my_str << endl;

   my_str.erase(remove(my_str.begin(), my_str.end(), 'A'), my_str.end()); //remove A from string
   cout << "Final string: " << my_str;


Initial string: ABAABACCABA
Final string: BBCCB
Published on 01-Apr-2019 17:59:17