【问题标题】:C++ s.replace function does not output spacesC++ s.replace 函数不输出空格
【发布时间】:2018-03-02 00:56:55
【问题描述】:

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

【问题讨论】:

  • 为什么使用while?这是一个无限循环......
  • 在替换后的输出s中加一个cout,看看能不能找出问题所在。 (并且为了将来参考,将不起作用不是传达任何含义或具有任何价值的问题描述,除非您具体解释您预期会发生什么以及发生了什么.)
  • 我正在从控制台获取该程序的输入。为了在这里提出问题,我定义了有限字符串。
  • 那么你选择了错误的模拟文本,因为它显然引入了一个不同的问题。阅读minimal reproducible example。并再次阅读我的评论。无论输入来自何处,它都适用。

标签: c++ string function replace


【解决方案1】:

就目前而言,这开始于:

是的,这是一个程序

它会在其中查找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(); 
}

【讨论】:

    猜你喜欢
    • 2018-05-17
    • 2014-12-14
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多