gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:31:47 25 4
gpt4 key购买 nike

这个特殊的赋值与从字符串中删除子字符串有关;我正在在线尝试一些斯坦福 SEE 类(class)来学习一些新语言。

目前我得到的是下面的内容,但是如果 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;
}

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

更新

接受了非常友善的建议并将我的代码修改为:

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;
}

但还是一样

大家还有什么想法吗?

最佳答案

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

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

除了不正确之外,取一个子字符串(这意味着分配一个新字符串)并计算其中的索引是非常低效的,除非优化器非常聪明。

此外,最终 returned += text.substr(lastfound,found); 也不正确:您需要添加文本的最后一 block ,而不是 found 索引(这很可能是空的,因为 lastfound 可以小于 found。更好的做法是 returned += text.substr(lastfound);

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

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

(由 J.F. 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;
}

关于C++ 字符串操作对我来说没有意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2709199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com