从 C++ 中的 std::string 中删除空格

2021-12-05 00:00:00 string whitespace c++ stl

在 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?

推荐答案

最好的做法是使用算法 remove_if 和 isspace:

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

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

现在算法本身不能改变容器(只能修改值),所以它实际上将值打乱并返回一个指向现在结束位置的指针.所以我们必须调用string::erase来实际修改容器的长度:

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

我们还应该注意,remove_if 最多只会制作一份数据副本.这是一个示例实现:

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

相关文章