题解 | #单词替换#
单词替换
https://www.nowcoder.com/practice/5b58a04679d5419caf62c2b238e5c9c7
#include <stdio.h>
#include<string.h>
int main() {
char str1[100];//字符串
char str2[10];//旧单词
char str3[10];//新单词
while (gets(str1) != NULL) {
gets(str2);
gets(str3);
char temp[100];
memset(temp, 0, sizeof(char));//初始化temp数组;
char *p;
for (p = strtok(str1, " "); p != NULL; p = strtok(NULL, " ")) {//利用strtook分割空格,每次分割一个单词,用p指针保存
if (strcmp(p, str2) == 0) { //若与原单词相等,则新单词写入temp,并加上一个空格字符
strcat(temp, str3);
strcat(temp, " \0");
}
else { //若与原单词不匹配,不改变单词写入temp,并加上一个空格字符
strcat(temp, p);
strcat(temp, " \0");
}
}
printf("%s\n", temp);//打印字符
}
return 0;
}
腾讯成长空间 5950人发布
查看15道真题和解析