AcWing 770. 单词替换
原题链接
中等
作者:
古娜拉黑暗之神
,
2021-02-20 14:47:28
,
所有人可见
,
阅读 264
第一种
/*
#include<iostream>
#include<string>
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(true){//检测是否是一个单词,标记是空格
if(j<s.size() && s[j]!=' '){
j++;
word = word + s[j];
cout<<word<<endl;
}else{
break;
}
}
//while(j < s.size() && s[j] != ' ') word = word + s[j], j ++;
i = j;
}
return 0;
}*/
#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;
}
第二种stringstresm
int main(){
string str;
getline(cin,str);
string a,b;
cin >> a >> b;
stringstream ssin(str); //将字符串初始化成字符串流
string temp;
while(ssin >> temp){
if(temp == a){
cout<<b << " ";
}else{
cout<< temp << " ";
}
}
return 0;
}