Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove whitespace in std::string [duplicate]

Tags:

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

This std::string

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

Into:

HELLOWORLDHELLOWORLD 
like image 623
Mr. Smith Avatar asked Jan 09 '13 10:01

Mr. Smith


1 Answers

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() ); } 
like image 153
CashCow Avatar answered Oct 06 '22 15:10

CashCow