一、现在有一个主串,需要将这个主串里面的部分连续子串替换成其他的子串,就可以用replace()函数来实现。
二、代码
#include <bits/stdc++.h>
using namespace std;
int main()
{
string str = "Hello, World! This is a test.";
// 用法 1: 从指定位置开始,替换指定长度的子串
// 从索引 7 开始,替换长度为 5 的子串为 "Universe"
str.replace(7, 5, "Universe");
cout << "替换后字符串: " << str << endl;
str = "Hello, World! This is a test.";
//用法2
string st1;
cin >> st1;
auto start = str.find(st1);
if(start != string::npos)
{
auto len = st1.size();
str.replace(start, len, "That");
cout << "再次替换后字符串: " << str << endl;
}
return 0;
}
三、在用法2里面,我使用了find()查找函数,可以检查其位置或者检查其是否在主串中。此外,我还使用了size()函数来确定一个字符串的长度(又几个字符,长度就是几)。
四、输出结果
