请编写程序,将给定主串 s 中的子串 sub_s 替换成另一个给定字符串 t,再输出替换后的主串 s。
输入格式:
输入给出 3 个非空字符串,依次为:主串 s、主串中待替换的子串 sub_s、将要替换掉 sub_s 的字符串 t。每个字符串占一行,长度不超过 1000 个字符,以回车结束(回车不算在字符串内)。
题目保证替换后的主串长度仍然不超过 1000 个字符。
输出格式:
在一行中输出替换后的主串 s。
输入样例 1:
This is a simple test.
is
at
输出样例 1:
That at a simple test.
输入样例 2:
This is a test.
simple
what
输出样例 2:
This is a test.
#include <bits/stdc++.h>
using namespace std;
int main() {
string s, sub_s, t;
getline(cin, s);
getline(cin, sub_s);
getline(cin, t);
size_t pos = 0;
while ((pos = s.find(sub_s, pos)) != string::npos) {
s.replace(pos, sub_s.length(), t);
pos += t.length(); // 移动位置到替换后的字符串之后,避免重复替换
}
cout << s << endl;
return 0;
}