How to remove certain characters from a string in C++?
I want to remove the "(", ")", and "-" characters from the string.
You can use the std::remove_if()
algorithm to remove only the characters you specify:
#include <iostream>
#include <algorithm>
#include <string>
bool IsParenthesesOrDash(char c)
{
switch(c)
{
case '(':
case ')':
case '-':
return true;
default:
return false;
}
}
int main()
{
std::string str("(555) 555-5555");
str.erase(std::remove_if(str.begin(), str.end(), &IsParenthesesOrDash), str.end());
std::cout << str << std::endl; // Expected output: 555 5555555
}
The std::remove_if()
algorithm requires something called a predicate, which can be a function pointer like the snippet above.
You can also pass a function object (an object that overloads the function call ()
operator). This allows us to create an even more general solution:
#include <iostream>
#include <algorithm>
#include <string>
class IsChars
{
public:
IsChars(const char* charsToRemove) : chars(charsToRemove) {};
bool operator()(char c)
{
for(const char* testChar = chars; *testChar != 0; ++testChar)
{
if(*testChar == c) { return true; }
}
return false;
}
private:
const char* chars;
};
int main()
{
std::string str("(555) 555-5555");
str.erase(std::remove_if(str.begin(), str.end(), IsChars("()- ")), str.end());
std::cout << str << std::endl; // Expected output: 5555555555
}
You can specify what characters to remove with the "()- "
string. In the example above I added a space so that spaces are removed as well as parentheses and dashes.
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, "()-" );