1
我最近开始学习C,并且偶然发现了这个练习。我试图找到所有以同一封信开头和结尾的单词。听起来很容易,但我不知道如何让我的程序重复数组中的每个单词的操作。C - 以相同字母开头和结尾的单词
浏览网页后,我决定使用strtok
,将数组分成单词,然后检查每个单词是否以相同的字母开头和结尾。我结束了这段代码,但它不工作,但编译器也没有显示任何问题。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
main(){
int i;
int found = 0;
char arr[1000];
char *token;
const char s[2] = " ";
printf("Write your line:\n");
scanf("%s", arr);
token = strtok(arr, s);
while(token!=NULL){
if(token[0] == (strlen(token)-1)){
found++;
}
token = strtok(NULL, s);
}
if(found > 0){
printf("Found %d words that start and end with the same letter.\n", found);
}
return 0;
}
任何人都可以向我解释我做错了什么?我一直在看它几个小时,我不知道有什么问题。
'''if(token [0] == token [strlen(token)-1])''' – Ronald
另外'scanf(“%s”,arr);'总是只接受一个单词。 – BLUEPIXY
@Ronald我试过了,但它只适用于第一个单词,忽略了其余 – Swaglina