答:
下面是使用C语言编写的程序,可以实现统计一个英文句子中最长的单词和第二长的字符数的功能:
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 100
void findLongestWords(char sentence[], char longestWord[], char secondLongestWord[]) {
char word[MAX_LENGTH];
int longestLength = 0, secondLongestLength = 0;
// 分割句子为单词
int i = 0, j = 0;
while (sentence[i] != '\0') {
if (sentence[i] == ' ' || sentence[i] == ',' || sentence[i] == '.') {
word[j] = '\0';
int length = strlen(word);
if (length > longestLength) {
secondLongestLength = longestLength;
strcpy(secondLongestWord, longestWord);
longestLength = length;
strcpy(longestWord, word);
} else if (length > secondLongestLength && length < longestLength) {
secondLongestLength = length;
strcpy(secondLongestWord, word);
}
j = 0;
} else {
word[j] = sentence[i];
j++;
}
i++;
}
}
int main() {
char sentence[MAX_LENGTH];
char longestWord[MAX_LENGTH], secondLongestWord[MAX_LENGTH];
printf("请输入一个英文句子:");
fgets(sentence, sizeof(sentence), stdin);
// 去除句子末尾的换行符
if (sentence[strlen(sentence) - 1] == '\n') {
sentence[strlen(sentence) - 1] = '\0';
}
findLongestWords(sentence, longestWord, secondLongestWord);
printf("最长的单词是:%s,字符数为:%d\n", longestWord, strlen(longestWord));
printf("第二长的单词是:%s,字符数为:%d\n", secondLongestWord, strlen(secondLongestWord));
return 0;
}
使用findLongestWords实现查找最长单词和第二长单词的功能。将输入的句子按照空格、逗号和句号进行分割,然后逐个单词比较其长度,找出最长的单词和第二长的单词。
在main函数,使用fgets函数获取用户输入的英文句子,并且去除末尾的换行符。然后调用findLongestWords函数来查找最长单词和第二长单词,并输出结果。
请这个程序假设输入的英文句子中只包含字母、空格、逗号和句号,不包含数字以及其他标点符号。如果输入的句子包含其他字符,程序可能无法正确处理。