remove whitespace in std::string

Mr. Smith picture Mr. Smith · Jan 9, 2013 · Viewed 56.7k times · Source

In C++, what's an easy way to turn:

This std::string

\t\tHELLO WORLD\r\nHELLO\t\nWORLD     \t

Into:

HELLOWORLDHELLOWORLD

Answer

CashCow picture CashCow · Jan 9, 2013

Simple combination of std::remove_if and std::string::erase.

Not totally safe version

s.erase( std::remove_if( s.begin(), s.end(), ::isspace ), s.end() );

For safer version replace ::isspace with

std::bind( std::isspace<char>, _1, std::locale::classic() )

(Include all relevant headers)

For a version that works with alternative character types replace <char> with <ElementType> or whatever your templated character type is. You can of course also replace the locale with a different one. If you do that, beware to avoid the inefficiency of recreating the locale facet too many times.

In C++11 you can make the safer version into a lambda with:

[]( char ch ) { return std::isspace<char>( ch, std::locale::classic() ); }