Re: remove certain characters from a string
Brad <brad@16systems.com> wrote:
I'm writing a function to remove certain characters from strings. For
example, I often get strings with commas... they look like this:
"12,384"
I'd like to take that string, remove the comma and return "12384"
What is the most efficient, fastest way to approach this?
The most obvious (if you want to replace the contents) is the
erase-remove idiom.
str.erase( remove( str.begin(), str.end(), ',' ), str.end() );
Thanks, works well with one character... How would I make it work with
several... like so:
#include <iostream>
std::string clean(std::string the_string)
{
char bad[] = {'.', ',', ' ', '|', '\0'};
std::string::size_type n = 0;
while ((n=the_string.find(bad, n))!=the_string.npos)
{
the_string.erase(n,1);
}
std::cout << the_string << std::endl;
return the_string;
}
int main()
{
clean("12,34.45|78 9");
return 0;
}
To make it work with several characters:
struct contains_any_of : unary_function< char, bool >
{
string str;
contains_any_of( const string& s ): str( s ) { }
bool operator()( char c ) const {
return find( str.begin(), str.end(), c ) != str.end();
}
};
str.erase( remove_if( str.begin(), str.end(),
contains_any_of( str2 ) ), str.end() );
Or to conform to your interface:
string clean( const string& str ) {
string result;
const char* const bad = "., |\0";
remove_copy_if( str.begin(), str.end(), back_inserter( result ),
contains_any_of( string( bad, bad + 5 ) ) );
return result;
}
Note: the "string( bad, bad + 5)" bit is necessary, otherwise the '\0'
will be clipped out, but maybe you didn't actually want to remove nulls
from the middle of the string?