题设单词句子长度都不大,所以可以储存一个二维char数组sentence,按空格隔开的顺序存放组成句子的单词,如下所示
| 单 | 单 |
单 |
单 |
... |
| 词 | 词 | 词 | 词 | ... |
| 1 |
2
|
3 | 4 | ... |
#include<cstdio>
#include<cstring>
char sentence[100][100];// dim0:sentence, dim1:word
char source[100];
char dest[100];
int main(){
char c;
int length = 0, charIdx=0;
while((c=getchar())!='\n'){
if(c==' '){
sentence[length++][charIdx]='\0';
charIdx=0;
}else{
sentence[length][charIdx++]=c;
}
}
sentence[length++][charIdx]='\0';
scanf("%s", source);
scanf("%s", dest);
for(int i=0;i<length;++i){
if(strcmp(sentence[i], source)==0){
printf(dest);
}else{
printf(sentence[i]);
}
printf(" ");
}
return 0;
}

京公网安备 11010502036488号