Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove spaces from std::string in C++

What is the preferred way to remove spaces from a string in C++? I could loop through all the characters and build a new string, but is there a better way?

like image 894
Steve Hanov Avatar asked Sep 17 '08 13:09

Steve Hanov


People also ask

How do you skip a space in a string C++?

The standard solution is to use the std::remove_if algorithm to remove whitespace characters from std::string using the Erase-remove idiom technique.

How do I remove spaces from a string?

strip()—Remove Leading and Trailing Spaces. The str. strip() method removes the leading and trailing whitespace from a string.


1 Answers

The best thing to do is to use the algorithm remove_if and isspace:

remove_if(str.begin(), str.end(), isspace); 

Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:

str.erase(remove_if(str.begin(), str.end(), isspace), str.end()); 

We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:

template<typename T, typename P> T remove_if(T beg, T end, P pred) {     T dest = beg;     for (T itr = beg;itr != end; ++itr)         if (!pred(*itr))             *(dest++) = *itr;     return dest; } 
like image 130
Matt Price Avatar answered Sep 17 '22 13:09

Matt Price