我有一个代码来替换给定字符串的子字符串的内容。它没有按我的预期工作。
根据我的理解,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 spanslen
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/