C ++ s.replace函数不输出空格

时间:2018-03-02 00:56:55

标签: c++ string function replace

我正在尝试解决为什么一个简单的程序来替换“#34; yes"单词"是和否"不管用。我的结论是,在是和否中有空格会导致这个问题。如果有办法让这个程序与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;
}

1 个答案:

答案 0 :(得分:2)

现在看来,这始于:

  

是的,这是一个程序

它会在其中查找yes,并替换它以便获得:

  

是的,这不是一个程序

然后它再次搜索并替换:

  

是和否,这不是一个程序

这可能足以使问题显而易见:因为替换包含要替换的值,所以进行替换会使其更接近完成。

为了让它在某个时刻完成,在每次替换之后,我们可能希望在该替换的 end 之后开始下一个搜索,而不是从字符串的开头重新开始,这个一般顺序:

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