题解 | #单词替换#
单词替换
https://www.nowcoder.com/practice/5b58a04679d5419caf62c2b238e5c9c7
#include<bits/stdc++.h>
using namespace std;
int main() {
string original, target,
replacement; //原始字符串、目标单词和替换单词
getline(cin, original);
getline(cin, target);
getline(cin, replacement);
//替换字符串中的指定单词
vector<string> words;
stringstream ss(original);//使用stringstream分割字符串为单词
string word;
while (ss >> word) {
if (word == target) {
words.push_back(
replacement);//如果当前单词与目标单词相同,替换为替换单词
} else {
words.push_back(word);//否则保留原单词
}
}
//输出替换后的结果
for (auto iter = words.begin(); iter != words.end(); iter++) {
cout << *iter << " ";
}
}

查看9道真题和解析