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?
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.
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.
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.
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, "()-" );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With