1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <string.h>

void countWords(){

char str[100] = "hello, my name is gaogaoProgramer, welcome to come here!";
int index;
long len = strlen(str);
int spaceIndex = 0; //从第一个下标开始算
int recordMax = 0; //单词空格之间下标最大差即为最长单词
int beforeIndex = 0,afterIndex = 0; //定义最长单词的前空格,后空格
for(index = 0; index < len; index++){
if(str[index] == 32){ //判断空格
if(index - spaceIndex > recordMax){
recordMax = index - spaceIndex;

//记录前下标和后下标。
beforeIndex = spaceIndex;
afterIndex = index;
}
spaceIndex = index;
}
}

printf("原始单词为:%s",str);
printf("\n单词空格之间下标最大差:%d 前下标:%d,后下标:%d",recordMax,beforeIndex,afterIndex);

//输出找到的单词;
printf("\n\n找到的最长度单词为:");
int charIndex;
for(charIndex = beforeIndex; charIndex< afterIndex ; charIndex++){
printf("%c",str[charIndex]);
}
}

评论