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 中删除空格


基础教程推荐
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01