C++字符串操作对我来说没有意义

Bol*_*ter 1 c++ string programming-languages

这个特定的赋值与从字符串中删除子串有关; 我正在网上尝试一些斯坦福SEE课程来学习一些新语言.

到目前为止,我已经得到了以下内容,但是如果text = "hello hello"remove ="el",它会陷入循环,但是如果我改变文本text = "hello hllo",它会起作用,让我觉得我做的事情显然是愚蠢的.

赋值中有一条规定,即不修改传入的字符串,而是返回一个新的字符串.

string CensorString1(string text, string remove){
    string returned;
    size_t found=0, lastfound=0;
    found = (text.substr(lastfound,text.size())).find(remove);
    while (string::npos != found ){
        returned += text.substr(lastfound,found);
        lastfound = found + remove.size();
        found = (text.substr(lastfound,text.size())).find(remove);
    }
    returned += text.substr(lastfound,found);
    return returned;
}
Run Code Online (Sandbox Code Playgroud)

指导将不胜感激:-)谢谢

UPDATE

给出了非常友好的建议,并将我的代码修改为:

string CensorString1(string text, string remove){
string returned;
size_t found=0, lastfound=0;
found = text.find(remove);
while (string::npos != found ){
    returned += text.substr(lastfound,found);
    lastfound = found + remove.length();
    found = text.find(remove,lastfound);
}
returned += text.substr(lastfound);
return returned;
}
Run Code Online (Sandbox Code Playgroud)

但仍然表现相同

还有更多的想法吗?

Vla*_*lad 5

found = (text.substr(lastfound,text.size())).find(remove);是不正确的.它返回搜索到的字符串的索引text.substr(lastfound,text.size()),但不是text.

您应该将此更改为found = text.find(text, lastfound);.

除了不正确之外,采用子字符串(这意味着,分配一个新字符串)并在其中计算索引是非常低效的,除非优化器是超级智能的.

此外,决赛returned += text.substr(lastfound,found);也是不正确的:你需要添加文本的最后一个块,而不是一个直到found索引(这很可能是空的,因为lastfound可能小于found.更好的是returned += text.substr(lastfound);

编辑:
在第二个示例中,您需要替换returned += text.substr(lastfound,found); returned += text.substr(lastfound,found-lastfound);.第二个参数substr是长度,而不是位置.

通过此更改,测试示例在我的测试程序中运行良好.

(加入JF Sebastian :)

string CensorString1(string const& text, string const& remove){
  string returned;
  size_t found = string::npos, lastfound = 0;
  do {
    found = text.find(remove, lastfound);
    returned += text.substr(lastfound, found-lastfound);
    lastfound = found + remove.size();
  } while(found != string::npos);
  return returned;
}
Run Code Online (Sandbox Code Playgroud)