题解 | #单词替换#
单词替换
https://www.nowcoder.com/practice/5b58a04679d5419caf62c2b238e5c9c7
要考虑的情况比较多,针对测试案例多改,写于2024.3.20
#include <iostream> #include <algorithm> #include <cstring> #include <cmath> using namespace std; int main() { int n, i, position; string s, a, b; string temp; getline(cin, s); getline(cin, a); getline(cin, b); // cout << s << "hdu" << a << "hdu" << b; // position = s.find(a); while (s.find(a) != string::npos) { // cout << position; // temp = s.substr(position, a.size() + 1); position = s.find(a); if (position != 0 && s[position + a.size()] == ' ' && s[position - 1] == ' ' || position == 0 && s[position + a.size()] == ' ') { s.erase(position, a.size()); s.insert(position, b); } else { s.erase(position, a.size()); for (i = 0; i < a.size(); i++) { s.insert(position, "*"); } } // position = s.find(a); } // cout << s << endl; while (s.find("*") != string::npos) { position = s.find("*"); s.erase(position, a.size()); s.insert(position, a); } cout << s << endl; return 0; }