从 C++ 中的 std::string 中删除空格 [英] Remove spaces from std::string in C++

查看:53
本文介绍了从 C++ 中的 std::string 中删除空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于从 C++ 中的 std::string 中删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆