std :: string :: erase没有像我预期的那样工作

时间:2018-04-10 19:59:35

标签: c++ c++11

这里有很多关于用逗号分割字符串的问题。我想再做一个。

#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,

我错过了什么吗?

3 个答案:

答案 0 :(得分:3)

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保持消除的元素完好无损,其中一些元素已被覆盖。

答案 1 :(得分:1)

有两个基于迭代器的string::erase版本。一个擦除单个字符,一个擦除范围。你必须添加范围的结尾才能摆脱所有这一切。

str1.erase(std::remove_if(str1.begin(), str1.end(),
                          [](unsigned char x){return std::isspace(x);}),
           str1.end());

答案 2 :(得分:0)

您对erase的调用使用单个迭代器参数重载,它会删除1个字符。添加str1.end()作为第二个参数以获得通常的删除+擦除习惯用法。