http://ac.jobdu.com/problem.php?pid=1111
-
题目描述:
-
输入一个字符串,以回车结束(字符串长度<=100)。该字符串由若干个单词组成,单词之间用一个空格隔开,所有单词区分大小写。现需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。
-
输入:
-
多组数据。每组数据输入包括3行,第1行是包含多个单词的字符串 s,第2行是待替换的单词a,(长度<=100)第3行是a将被替换的单词b。(长度<=100)s, a, b 最前面和最后面都没有空格.
-
输出:
-
每个测试数据输出只有 1 行,将s中所有单词a替换成b之后的字符串。
-
样例输入:
-
You want someone to help you You I
-
样例输出:
-
I want someone to help you
-
#include <iostream> #include <string> #include <sstream> using namespace std; int main(){ string s, a, b; while (getline(cin, s)){ cin >> a >> b; cin.get(); stringstream ss(s); string tmp; ss >> tmp; if (tmp == a) cout << b; else cout << tmp; while (ss >> tmp){ if (tmp == a) cout << " " << b; else cout << " " << tmp; } cout << endl; } return 0; }
#include <stdio.h>
#include <string.h>
int main(){
char s[101], a[101], b[101];
while (gets(s)){
scanf("%s%s", a, b);
getchar();
char *p = strtok(s, " ");
int flag = 1;
while (p){
if (flag){
flag = 0;
}
else{
printf(" ");
}
if (strcmp(p, a) == 0)
printf(b);
else
printf(p);
p = strtok(NULL, " ");
}
printf("\n");
}
return 0;
}