Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 278
SD. Avatar asked May 05 '11 01:05

SD.


People also ask

How do I remove a specific character from a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do I remove the last 3 characters from a string?

To remove the last three characters from the string you can use string. Substring(Int32, Int32) and give it the starting index 0 and end index three less than the string length. It will get the substring before last three characters.

How do I remove two characters from a string?

Use the String. slice() method to remove the last 2 characters from a string, e.g. const removedLast2 = str. slice(0, -2); . The slice method will return a new string that doesn't contain the last 2 characters of the original string.


1 Answers

   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, "()-" ); 
like image 126
Eric Z Avatar answered Nov 04 '22 03:11

Eric Z