Remove spaces from std::string in C++(从 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 中删除空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C++ 中的 std::string 中删除空格
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
