Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

10 Answers

up vote 84 down vote accepted

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;
}
share|improve this answer
16  
Because 'isspace' has overloads, you will probably need to qualify the generic code to use ::isspace (the C implementation that doesn't take a locale) or be greeted with cryptic template instantiation errors. – Bklyn Jan 5 '09 at 15:10
1  
All - be wary of the above method (The two single lines, not the templated version, although it may have the same issue). I used it in a project without realizing that it isn't always correct. For example, if you pass it the string "1 + 1" it returns "1+11". I switched to @rupello 's method below and it worked fine for this case. Happy coding! – JoeB Apr 19 '12 at 18:43
@Joe The answer explicitly mentions that you need to call erase afterwards. That will return the correct result. – Konrad Rudolph Sep 15 '12 at 7:17
4  
-1 this use of isspace is UB for all character sets except original 7-bit ASCII. C99 §7.4/1. it does not surprise me that it's been upvoted to the tune of 71 votes by now, in spite of being Very Bad Advice. – Cheers and hth. - Alf Oct 25 '12 at 13:48

You can use this solution for removing a char:

#include < algorithm >

str.erase(remove(str.begin(), str.end(), char_to_remove), str.end());
share|improve this answer
#include < string.h > using namespace std; – sgmart May 21 at 23:50

From gamedev

string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
share|improve this answer
5  
This will not compile on standards-conforming implementations because of the locale-taking overloads of std::isspace. You'll need to use ::isspace or perform some unreadable machinations with std::bind2nd. Isn't generic code beautiful? – Bklyn Jan 5 '09 at 15:23
string replaceinString(std::string str, std::string tofind, std::string toreplace)
{
        size_t position = 0;
        for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
        {
                str.replace(position ,1, toreplace);
        }
        return(str);
}

use it:

string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");
share|improve this answer

Hi, you can do something like that. This function deletes all spaces.

string delSpaces(string &str) 
{
   str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
   return str;
}

I made another function, that deletes all unnecessary spaces.

string delUnnecessary(string &str)
{
    int size = str.length();
    for(int j = 0; j<=size; j++)
    {
        for(int i = 0; i <=j; i++)
        {
            if(str[i] == ' ' && str[i+1] == ' ')
            {
                str.erase(str.begin() + i);
            }
            else if(str[0]== ' ')
            {
                str.erase(str.begin());
            }
            else if(str[i] == '\0' && str[i-1]== ' ')
            {
                str.erase(str.end() - 1);
            }
        }
    }
    return str;
}
share|improve this answer
1  
slim and right to the point, thanks. – Felipe Gringo Apr 10 at 20:14

For trimming, use boost string algorithms:

#include <boost/algorithm/string.hpp>

using namespace std;
using namespace boost;

// ...

string str1(" hello world! ");
trim(str1);      // str1 == "hello world!"
share|improve this answer
1  
-1: This trims; it does not remove all whitespace. – Thomas Eding Aug 7 '12 at 18:08
#include <stringthing>

using namespace stringpower;

...

string str1(" hello world! ");
str1.spacechop(str1);      // str1 == "helloworld!"
share|improve this answer
17  
What the hell is stringthing/stringpower/spacechop? – Matteo Italia Mar 13 '10 at 22:37

Can you use Boost String Algo? http://www.boost.org/doc/libs/1_35_0/doc/html/string_algo/usage.html#id1290573

erase_all(str, " ");
share|improve this answer
It is slower than the remove_if(str.begin(), str.end(), isspace); that Matt Price mentioned. I don't know why. Actually, all the boost stuff, that have STL alternatives, are slower than the corresponding gcc ones (All the ones I tested). Some of them are immensely slower! (up to 5 times in unordered_map inserts) Maybe it is because of the CPU cache of the shared environment or something like it. – Tolga Aug 14 '12 at 20:23

I'm afraid it's the best solution that I can think of. But you can use reserve() to pre-allocate the minimum required memory in advance to speed up things a bit. You'll end up with a new string that will probably be shorter but that takes up the same amount of memory, but you'll avoid reallocations.

EDIT: Depending on your situation, this may incur less overhead than jumbling characters around.

You should try different approaches and see what is best for you: you might not have any performance issues at all.

Dave

share|improve this answer
remove_if makes at most one copy of each value. So there really isn't that much overhead relative to what needs to be done. – Matt Price Sep 17 '08 at 14:04
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
share|improve this answer
6  
My up-vote for the canonical erase/remove idiom. Can be made into a one liner: str.erase (std::remove (str.begin(), str.end(), ' '), str.end()); – Bklyn Jan 5 '09 at 15:08
Worked perfectly, thanks. – user462608 Jan 10 at 10:12
Great method on how todo this, works perfectly! – Arno May 5 at 9:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.