题解 | #单词替换#
单词替换
https://www.nowcoder.com/practice/5b58a04679d5419caf62c2b238e5c9c7
使用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; } }