std::string::擦除没有按我预期工作
std::string::erase doesn't work as I expected
这里有很多关于用逗号拆分字符串的问题。我正在尝试制作另一个。
#include<iostream>
#include<algorithm>
#include<string>
#include<cctype>
int main()
{
std::string str1 = "1.11, 2.11, 3.11, 4.11, 5.11, ";
str1.erase(std::remove_if(str1.begin(), str1.end(), [](unsigned char x){return std::isspace(x);}));
std::cout<<"New string = "<<str1<<std::endl;
return 0;
}
但是我在下面得到了意想不到的输出。
New string = 1.11,2.11,3.11,4.11,5.11, 4.11, 5.11,
我错过了什么吗?
std::remove_if
将未删除的元素移动到字符串的前面,并将迭代器返回到要擦除的第一个元素。 使用单个迭代器参数 erase
,它只擦除单个元素。要擦除所有匹配的字符,您需要通过传递迭代器来使用两个参数版本end
:
str1.erase(
std::remove_if(
str1.begin(),
str1.end(),
[](unsigned char x){return std::isspace(x);}
),
str1.end() // this was missing
);
如果您想知道为什么末尾有一些非空格字符,std::remove_if
不需要保持消除的元素完整,并且其中一些已被覆盖。
有两个基于迭代器的string::erase
版本。一个擦除单个字符,另一个擦除范围。您必须添加范围的末尾才能摆脱所有范围。
str1.erase(std::remove_if(str1.begin(), str1.end(),
[](unsigned char x){return std::isspace(x);}),
str1.end());
对 erase
的调用使用单个迭代器参数重载,该重载会删除 1 个字符。添加str1.end()
作为第二个参数,以获得通常的删除+擦除习惯用法。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- <string> 结构中的矢量无法正常工作
- string.find() 无法正常工作
- std::string::擦除没有按我预期工作
- 'const std::string&s = nullptr' 如何作为可选参数工作
- `std :: string :: find_last_of()如何实际工作
- std::string 上的 substr 无法正常工作,因为存在一些不可见但看起来像空格的字符
- "string::erase"如何在 cpp 中工作?
- std::string 赋值运算符如何工作
- 我在不使用string.h的情况下写了一个C++回文.在没有 Do-While 循环的情况下,它可以正常工作.但是当我尝
- std::string::find在c++中未按预期工作
- c ++比较std::string将无法工作,如果我不使用Code::Blocks但cygwin编译
- 采用“std::string”的显式构造函数得到“char*”,工作正常
- getline(cin,string)与cin.ignore()一起不工作
- basename-freebsd使用std::string可以正常工作,但不使用
- c++转换为String最终停止工作
- std::atomic<std::string> 是否正常工作?
- 我的指向 std::string 对象的指针列表无法正常工作,我无法弄清楚为什么
- Std::string不能与Std::set一起工作