c++ - 在 C++ 中替换给定字符串的子字符串

标签 c++ string replace substring

我有一个代码来替换给定字符串的子字符串的内容。它没有按我的预期工作。

根据我的理解,s3.find("they") 将返回 6。由于 pos 与 string::npos 不同,因此,从位置 6 开始,s3 中的 2 个字符被字符串 s4 替换。所以,s3 将是“There boey go again!”更换后。然而,s3 的输出是“鲍勃和比尔又来了!”。谁能帮忙解释一下吗?

#include <iostream>
#include <string>
using namespace std;
string prompt("Enter a line of text: "),
line( 50, '*');

int main()
  {

    string s3("There they go again!"),
           s4("Bob and Bill");
    int pos = s3.find("they");
    if( pos != string::npos )
        s3.replace(pos, 2, s4);
    cout << s3 << endl;
    cout << s4 << endl;
    return 0;
}

最佳答案

Yet, the output of s3 is, "There Bob and Bill go again!". Could anyone help to explain?

不完全是。输出是“Bob 和 Billey 又走了”。从单词 they 开始,它采用了前两个字符 (th) 并将其替换为 Bob 和 Bill。结果是鲍勃和比利又来了!

此行为与本文档对 std::string::replace 的解释一致。 :

Replaces the portion of the string that begins at character pos and spans len characters (or the part of the string in the range between [i1,i2)) by new contents:

(1) string Copies str.

如果您希望输出为“There Boey go Again!”,您可以这样做:

int size = 2; // amount of characters that should be replaced
if (pos != string::npos)
    s3.replace(pos, size, s4.substr(0, size));

关于c++ - 在 C++ 中替换给定字符串的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58627134/

相关文章:

c++ - Caffe Sigmoid 交叉熵损失层损失函数

java - JNI 加载具有依赖项的 jar

string - Clojure 中字符串向量的串联

C语言,如何求二维数组中一个单词的长度?

c - 随机播放,然后查找并替换二维数组中的重复项 - 无需排序

c++ - 运行最基本的 sfml 应用程序时的性能问题

c++ - 在 Windows 中从父进程继承句柄

c - 在套接字 C 中发送字符串?

regex - 将每列中的第一个匹配项替换为 bash

java - 使用正则表达式替换字符串中出现的所有单词