c语言求最长单词,与其长度,还有最长单词的个数
时间: 2023-06-02 11:01:58 浏览: 107
以下是一个求最长单词的示例程序,它使用fgets函数从标准输入读取一行文本,然后使用strtok函数将该行文本分解为单词,通过比较单词长度来确定最长单词,以及计算最长单词的个数。
```
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 100
int main() {
char line[MAX_LENGTH];
char *word;
int max_length = 0;
int count = 0;
printf("Enter a line of text: ");
fgets(line, MAX_LENGTH, stdin);
word = strtok(line, " ,.;:\n");
while (word != NULL) {
int length = strlen(word);
if (length > max_length) {
max_length = length;
count = 1;
} else if (length == max_length) {
count++;
}
word = strtok(NULL, " ,.;:\n");
}
printf("The longest word has %d characters.\n", max_length);
printf("There %s %d word%s with that length.\n",
count == 1 ? "is" : "are", count, count == 1 ? "" : "s");
return 0;
}
```
示例输出:
```
Enter a line of text: The quick brown fox jumps over the lazy dog.
The longest word has 5 characters.
There is 1 word with that length.
```
该程序使用MAX_LENGTH常量来定义输入行和单词的最大长度,并使用fgets函数从标准输入读取一行文本。然后,它使用strtok函数将该行文本分解为单词,并通过循环检查每个单词的长度来确定最长单词的长度和个数。最后,程序输出最长单词的长度和个数。
阅读全文