首页 > 解决方案 > 如何正确使用 string::erase

问题描述

我不确定我是否正确使用了 string::erase。我正在尝试创建一个函数来查找子字符串并将其从原始字符串中删除。我已经测试过 string:find 有效,但是在擦除时,相同的字符串仍然存在。

源文件 .cpp

Sentence operator-(const Sentence& arg1, const Sentence& arg2)
{
    Sentence result = arg1;

    string str = arg1.get_sentence();
    string str2 = arg2.get_sentence();

    bool found = false;


    if (str2.find(str) != std::string::npos) {

        found = true;

    } else if (found == true) {

        str2.erase(str.find(str), str2.size());

    }


    return str2;

}

标签: c++substringerase

解决方案


您的代码中有两个错误。

首先,您搞砸了if语句逻辑,因此永远不会执行擦除语句(如另一个答案中所指出的)。

是你用std::string::erase()错了。第一个参数应该是要删除的第一个字符的索引,第二个参数应该是要删除的字符总数。

由于您已经搜索了子字符串,因此您可以重新循环该信息以用于erase. 因此,我们的代码的正确版本是

auto pos = str.find(sub);
if(pos != std::string::npos)
    str.erase(pos,sub.size());

如果要删除所有出现的子字符串,可以使用for循环:

for(auto pos=str.find(sub); pos!=std::string::npos; pos=str.find(sub))
    str.erase(pos,sub.size());

推荐阅读