c++ - 如何正确使用 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;
}
解决方案
您的代码中有两个错误。
首先,您搞砸了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());
推荐阅读
- sql - 需要如何选择 or 条件?
- javascript - 表单在函数调用时消失
- linux - 如何正确启用 Oracle 数据库上的操作审计?
- c# - 如何在c#中修改xml文件
- scala - 因“juNoSuchElementException:未定义名为“notStartedRefIds”的属性而崩溃
- random - 字典中随机 if 函数中没有用户输入的 MadLib
- python-3.x - 在函数定义中使用 elif 而不是 else 时显示异常的 return 语句
- python - Python - 32 位版本与 64 位版本的位移
- swashbuckle - 来自 adsl.js 的奇怪随机观众错误
- c# - C#,分配内部委托