解法1
直接找对应单词
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string s, a, b;
getline(cin, s);
cin >> a >> b;
for (int i = 0; i < s.size(); i ++)
{
string word;
int j = i;
while(j < s.size() && s[j] != ' ') word = word + s[j], j ++;
if (word == a) cout << b << " ";
else cout << word << " ";
i = j;
}
return 0;
}
解法2
正则匹配
#include <iostream>
#include <regex>
using namespace std;
int main(){
string s,a,b;
getline(cin,s);
cin>>a>>b;
cout<<regex_replace(s,regex("\\b" + a + "\\b"),b)<<endl;
return 0;
}
解法3
sstream
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string s, a, b;
getline(cin, s);
cin >> a >> b;
stringstream ssin(s);
string str;
while (ssin >> str)
// 遇到空格停止,所以可以分割单词
if (str == a) cout << b << ' ';
else cout << str << ' ';
return 0;
}