题目链接:http://codeup.cn/problem.php?cid=100000580&pid=3
题目描述
输入一个字符串,以回车结束(字符串长度<=100)。该字符串由若干个单词组成,单词之间用一个空格隔开,所有单词区分大小写。现需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。
输入
多组数据。每组数据输入包括3行,
第1行是包含多个单词的字符串 s,
第2行是待替换的单词a,(长度<=100)
第3行是a将被替换的单词b。(长度<=100)
s, a, b 最前面和最后面都没有空格。
输出
每个测试数据输出只有 1 行,
将s中所有单词a替换成b之后的字符串。
样例输入
I love Tian Qin
I
You
样例输出
You love Tian Qin
代码
方法1 :
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1[101], str2, str3;
while(cin >> str1[0]) {
int i = 1;
while(getchar()!='\n')
cin >> str1[i++];
cin >> str2;
cin >> str3;
for(int j = 0; j < i; j++) {
if(str1[j] == str2)
cout << str3 << ' ';
else
cout << str1[j] << ' ';
}
cout <<endl;
}
return 0;
}
方法2 :
#include<stdio.h>
#include<string.h>
int main() {
char str1[110];
char str2[110];
char str3[110];
while(gets(str1)){
gets(str2);
gets(str3);
int len1 = strlen(str1),
len2 = strlen(str2),
len3 = strlen(str3);
int r = 0, h = 0, i;
char ans[110][110] = {0};
for(i = 0; i < len1; i++) { //存储每个单词
if(str1[i] != ' ')
ans[r][h++] = str1[i];
else{
ans[r][h] = '\0';
r++;
h = 0;
}
}
ans[r][h]='\0'; //
for(i = 0; i <= r; i++){ //依次比较单词
if(!strcmp(ans[i], str2))
strcpy(ans[i], str3);
/*
if(str2[0] == ans[i][0])
for(h = 1; h < len2; h++){
if(str2[h] != ans[i][h])
continue;
}
if(h == len2)
for(h = 0; h < len3; h++)
ans[i][h] = str3[h];
*/
}
for(i = 0; i <= r; i++) { //输出
if(i > 0)
printf(" ");
printf("%s", ans[i]);
}
printf("\n");
}
return 0;
}