Remove spaces from std::string in C++

2019-01-01 06:04发布

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?

标签: c++ stl
12条回答
笑指拈花
2楼-- · 2019-01-01 07:02

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.

查看更多
何处买醉
3楼-- · 2019-01-01 07:06

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;
}
查看更多
琉璃瓶的回忆
4楼-- · 2019-01-01 07:07
string removespace(string str)
{    
    int m = str.length();
    int i=0;
    while(i<m)
    {
        while(str[i] == 32)
        str.erase(i,1);
        i++;
    }    
}
查看更多
长期被迫恋爱
5楼-- · 2019-01-01 07:10

From gamedev

string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
查看更多
时光乱了年华
6楼-- · 2019-01-01 07:10

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;
}
查看更多
爱死公子算了
7楼-- · 2019-01-01 07:11
std::string::iterator end_pos = std::remove(str.begin(), str.end(), ' ');
str.erase(end_pos, str.end());
查看更多
登录 后发表回答