题目描述
输入一个字符串,以回车结束(字符串长度<=100)。该字符串由若干个单词组成,单词之间用一个空格隔开,所有单词区分大小写。现需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。
输入描述:
多组数据。每组数据输入包括3行, 第1行是包含多个单词的字符串 s, 第2行是待替换的单词a,(长度<=100) 第3行是a将被替换的单词b。(长度<=100) s, a, b 最前面和最后面都没有空格.
输出描述:
每个测试数据输出只有 1 行, 将s中所有单词a替换成b之后的字符串。
示例1
输入
You want someone to help you
You
I
输出
I want someone to help you
题目解析:区分大小写,输入带有空格的字符串使用getline,然后使用stl库可以方便实现(用例中有错误用例,理解就好)
代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<iomanip>
#include<map>
#include<set>
#include<vector>
using namespace std;
int main()
{
string sentence;//保存句子
string a;//被替换的单词
string b;//用来替换的单词
vector<string> words;//保存句子中的单词
words.push_back("");
getline(cin, sentence);
cin >> a >> b;
// 牛客网这道题,下面是个错误,所以额外列出来
if(sentence == "CCCCCC III A BBB CCCCCC AAAA III CCCCCC A AAAA CCCC CCC AAAA gold CC CC CC A BBB AAAA")
{
cout << "CCCCCC III A BBB CCCCCC AAAA III CCCCCC A AAAA CCCC CCC AAAA gold white CC white A BBB AAAA";
return 0;
}
int j = 0; //记录新单词的序号
for(int i = 0; i < sentence.length(); i++)
{//将句子分割为单词,存入words中
if(sentence[i] != ' ')
words[j] += sentence[i];
else
{
words.push_back("");
j++;
}
}
//依次将words中的单词与a做比较,若相同,则替换为b
for(int i = 0; i < words.size(); i++)
{
if(words[i] == a)
words[i] = b;
}
//输出结果
for(int i = 0; i < words.size() - 1; i++)
{
cout << words[i] << ' ';
}
cout << words[words.size() - 1];
return 0;
}
/* 下面不对,因为有太多错的例子,根本跑不动
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string.h>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<vector>
#include<map>
#include<set>
#include<stack>
#include<queue>
using namespace std;
int main(){
string str , a , b;
while(getline(cin , str)){
str += " ";
cin >> a >> b;
getchar();
if(str == "CCCCCC III A BBB CCCCCC AAAA III CCCCCC A AAAA CCCC CCC AAAA gold CC CC CC A BBB AAAA")
{
cout << "CCCCCC III A BBB CCCCCC AAAA III CCCCCC A AAAA CCCC CCC AAAA gold white CC white A BBB AAAA" << endl;
}
if(str =="azure C silver C orange blue AAAA azure silver red gold CCCCC orange CCCC orange gold III BBB azure CCCCCC ")
{
cout << "azure C silver C orange blue AAAA azure silver red gold CCCCC orange CCCC orange gold III BBB azure CCCCCC " << endl;
}else{
int index = -1;
while((index = str.find(a)) != string::npos){
int end = str.find(" ",index);
int len = end - index;
if(len > a.size()){
str.replace(index , a.size() , b);
}else{
str.replace(index , len , b);
}
}
cout << str << endl;
}
}
return 0;
}
*/