使用find函数时会将所有匹配上的字符串全部替换掉,所以要在单词的前后加上空格
#include<iostream>
#include<string>
using namespace std;
int main() {
string str;
string oldstr, newstr;
while (getline(cin, str))
{
str = ' ' + str;
cin >> oldstr;
oldstr = ' ' + oldstr + ' ';
cin >> newstr;
newstr = ' ' + newstr + ' ';
while (str.find(oldstr) != string::npos )
{
int pos = str.find(oldstr);
str.erase(pos, oldstr.size());
str.insert(pos, newstr);
}
str.erase(0, 1);
cout << str << endl;
}
}



京公网安备 11010502036488号