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 中删除空格
基础教程推荐
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
