我不确定我是否正确使用了 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;
}
最佳答案
您的代码中有两个错误。
首先您搞砸了 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());
关于c++ - 如何正确使用 string::erase,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55997040/