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

replace a substring of a given string in c++

本文关键字:字符串 c++ 替换      更新时间:2023-10-16

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

根据我的理解,s3.find("they"(将返回6。由于pos与字符串::npos不同,因此,从位置6开始,s3中的2个字符被字符串s4替换。所以,s3在替换后会是"又来了!"。然而,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;
}

然而,s3的输出是"Bob和Bill又来了!"。能够有人帮忙解释吗?

不完全是。输出为"Bob和Bill再次出发"。从单词they开始,它取前两个字符(th(,并用Bob and Bill替换它们。结果是There Bob and Billey go again!

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

替换字符串中以字符pos和跨越len个字符(或介于[i1,i2((通过新内容:

(1( 字符串复制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));