Remove Spaces from Std::String in C++

Remove spaces from std::string in C++

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;
}

Remove spaces from a string in C++

std::string::erase returns an iterator, but you don't have to use it. Your original string is modified.

string removeSpaces(string input)
{
input.erase(std::remove(input.begin(),input.end(),' '),input.end());
return input;
}

Best way to remove white spaces from std::string

Edit: upgraded to locale-aware trait. Thanks user657267 !

Standards algorithms are neat !

s.erase(std::remove_if(
begin(s), end(s),
[l = std::locale{}](auto ch) { return std::isspace(ch, l); }
), end(s));

Live on Coliru

That was for in-place modification, if you need to keep the original string however :

std::string s2;
s2.reserve(s.size());
std::remove_copy_if(
begin(s), end(s),
std::back_inserter(s2),
[l = std::locale{}](auto ch) { return std::isspace(ch, l); }
);

Live on Coliru

remove whitespace in std::string

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() ); }

Removing all spaces from a string

First off, std::isspace is declared in <cctype> so include that.

Secondly, you need to disambiguate the overload by casting the function to an explicit type:

str.erase(
remove_if(str.begin(), str.end(), static_cast<int(*)(int)>(isspace)),
str.end());

Third, as James remarked, this causes undefined behaviour for all characters which aren’t in the ASCII range, and since you cannot generally exclude this, you need to make an effort to ensure that only positive character codes are passed to std::isspace:

bool char_isspace(char c) {
return std::isspace(static_cast<unsigned char>(c));
}



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

Removing Whitespace from string in C++

str.erase(str.find(' '), 1);

Explanation:

  1. The call to str.find returns the position (index) of the space.
  2. The call to str.erase removes one character, starting at that position.

Remove whitespace from string excluding parts between pairs of and ' C++

No, there is not such a routine ready.

You may build your own though.

You have to loop over the string and you want to use a flag. If the flag is true, then you delete the spaces, if it is false, you ignore them. The flag is true when you are not in a part of quotes, else it's false.

Here is a naive, not widely tested example:

#include <string>
#include <iostream>
using namespace std;

int main() {
// we will copy the result in new string for simplicity
// of course you can do it inplace. This takes into account only
// double quotes. Easy to extent do single ones though!
string str("\"Hello, World!\" I am a string");
string new_str = "";
// flags for when to delete spaces or not
// 'start' helps you find if you are in an area of double quotes
// If you are, then don't delete the spaces, otherwise, do delete
bool delete_spaces = true, start = false;
for(unsigned int i = 0; i < str.size(); ++i) {
if(str[i] == '\"') {
start ? start = false : start = true;
if(start) {
delete_spaces = false;
}
}
if(!start) {
delete_spaces = true;
}
if(delete_spaces) {
if(str[i] != ' ') {
new_str += str[i];
}
} else {
new_str += str[i];
}

}
cout << "new_str=|" << new_str << "|\n";
return 0;
}

Output:

new_str=|"Hello, World!"Iamastring|



Related Topics



Leave a reply



Submit