void findLongestWord(char str[])
{
int max = 0, //最长单词的长度
len = 0;//每个单词的长度
int startingIndex = 0, endIndex = 0;
int strIndex = 0;//数组下标(控制循环)
while (str[strIndex] != '\0')
{
if (str[strIndex] != ' ')
{
len++;
}
else
{
if (max < len)
{
max = len;
startingIndex = strIndex - max; //最长的单词的开始的下标等于数组元素为空格的下标减去单词长度
endIndex = strIndex;
}
len = 0;
}
strIndex++;
}
if (max < len) //判断最后一个单词是否比最长的单词长
{
max = len;
startingIndex = strIndex - max;
endIndex = strIndex;
}
printf("The longest word is: ");
for (int k = startingIndex; k < endIndex; k++)
printf("%c", str[k]);
printf("\n");
}
int main()
{
//char str[100] = "This is a sentence"; //与gets同等效果
char str[200];
gets(str);
//scanf("%c", &str); //不能这么输入,scanf中空格代表输入结束并把回车符留在缓存中;gets可以接收空格并把回车符转换为'\0'
findLongestWord(str);
return 0;
}
用gets不用scanf的原因:scanf不能接收空格遇到空格就代表输入结束,scanf把回车符留在缓存中;gets可以接收空格,把回车符转换为 '\0';gets的返回值为char类型scanf返回值为int类型;gets只能用于输入字符串,而scanf可以输入很多类型的变量