c语言求最长单词,与其长度,还有个数
时间: 2023-06-02 17:01:53 浏览: 61
以下是一个求解最长单词及其长度和个数的示例程序:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char sentence[1000]; // 假设输入的句子不超过1000个字符
printf("请输入一个句子:\n");
fgets(sentence, 1000, stdin); // 从标准输入获取句子字符串
sentence[strlen(sentence) - 1] = '\0'; // 将最后的换行符替换为字符串结束符'\0'
char longest_word[100]; // 假设最长的单词不超过100个字符
int longest_length = 0; // 最长的单词长度
int word_count = 0; // 单词个数
char* word = strtok(sentence, " "); // 用空格分隔句子,获取第一个单词
while (word != NULL) { // 如果还有单词
int length = strlen(word); // 获取当前单词的长度
if (length > longest_length) { // 如果当前单词比最长单词更长
strcpy(longest_word, word); // 更新最长单词
longest_length = length; // 更新最长单词长度
}
word_count++; // 统计单词个数
word = strtok(NULL, " "); // 获取下一个单词
}
printf("最长的单词是:%s,长度为:%d,共有%d个单词。\n", longest_word, longest_length, word_count);
return 0;
}
```
示例输入:
```
请输入一个句子:
The quick brown fox jumps over the lazy dog.
```
示例输出:
```
最长的单词是:jumps,长度为:5,共有9个单词。
```