我试图解决为什么一个简单的程序用“是和否”替换“是”这个词是行不通的。我的结论是,在是和否中有空格会导致这个问题。如果有办法让这个程序与s.replace函数一起正常工作?
谢谢!
string s = "yes this is a program";
while (s.find("yes") != string::npos) {
s.replace(s.find("yes"), 3, "yes and no");
}
编辑:下面是完整的程序,其中包含字符串的控制台输入。
int main() {
string s;
cout << "Input: ";
getline(cin, s);
while (s.find("yes") != string::npos) {
s.replace(s.find("yes"), 3, "yes and no");
}
cout << s << endl;
return 0;
}
现在看来,这开始于:
是的,这是一个程序
它在那里寻找yes
,并替换它,所以你得到:
是的,不,这是一个程序
然后它再次搜索并替换:
是和否,这不是一个程序
这可能足以使问题显而易见:因为替换包含要替换的值,所以进行替换会使其更接近完成。
为了使它在某个时刻完成,在每次替换之后,我们可能希望在替换结束后开始下一次搜索,而不是从字符串的开头重新开始,这是一般顺序:
string::size_type pos = 0; // start from the beginning
std::string replacement = "yes and no";
while ((pos=s.find("yes", pos)) != string::npos) {
s.replace(pos, 3, replacement);
// adjust the starting point of the next search to the end of the
// replacement we just did.
pos += replacement.length();
}