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

SD. picture SD. · May 5, 2011 · Viewed 277.6k times · Source

For example I have a user input a phone number.

cout << "Enter phone number: ";
INPUT: (555) 555-5555
cin >> phone;

I want to remove the "(", ")", and "-" characters from the string. I've looked at the string remove, find and replace functions however I only see that they operate based on position.

Is there a string function that I can use to pass a character, "(" for example, and have it remove all instances within a string?

Answer

Eric Z picture Eric Z · May 5, 2011
   string str("(555) 555-5555");

   char chars[] = "()-";

   for (unsigned int i = 0; i < strlen(chars); ++i)
   {
      // you need include <algorithm> to use general algorithms like std::remove()
      str.erase (std::remove(str.begin(), str.end(), chars[i]), str.end());
   }

   // output: 555 5555555
   cout << str << endl;

To use as function:

void removeCharsFromString( string &str, char* charsToRemove ) {
   for ( unsigned int i = 0; i < strlen(charsToRemove); ++i ) {
      str.erase( remove(str.begin(), str.end(), charsToRemove[i]), str.end() );
   }
}
//example of usage:
removeCharsFromString( str, "()-" );