编写程序,统计一个英文句子中最长的单词和第二长的字符数。
程序设计要求:
(1)必须支持用有逗号和句号的英语句子来输入。
(2)两个长度不能相同,比如输入的单词长度为4,4,4,3,3,2,则需要输出4和3而不是4和4。
(2)输入的英语句子无需包含数字以及除逗号和句号意外的其他标点符号。
引用 皆我百晓生 小程序回复内容作答:
下面是一个使用 C 语言编写的程序,可以统计一个英文句子中最长的单词和第二长的字符数。请注意,该程序假设单词之间只用空格分隔,输入的英语句子不包含数字以及除逗号和句号外的其他标点符号。
#include <stdio.h>
#include <string.h>
#define MAX_LENGTH 100
void getLongestWords(char* sentence, char* longestWord, char* secondLongestWord);
int main() {
char sentence[MAX_LENGTH];
char longestWord[MAX_LENGTH];
char secondLongestWord[MAX_LENGTH];
printf("请输入一个英文句子:\n");
fgets(sentence, MAX_LENGTH, stdin);
// 替换句子中的逗号和句号为空格
for (int i = 0; i < strlen(sentence); i++) {
if (sentence[i] == ',' || sentence[i] == '.') {
sentence[i] = ' ';
}
}
getLongestWords(sentence, longestWord, secondLongestWord);
printf("最长的单词:%s\n", longestWord);
printf("第二长的字符数:%ld\n", strlen(secondLongestWord));
return 0;
}
void getLongestWords(char* sentence, char* longestWord, char* secondLongestWord) {
char word[MAX_LENGTH];
int longestLength = 0;
int secondLongestLength = 0;
char* token = strtok(sentence, " ");
while (token != NULL) {
// 检查当前单词的长度
int wordLength = strlen(token);
if (wordLength > longestLength) {
// 如果当前单词比最长单词还长
secondLongestLength = longestLength;
longestLength = wordLength;
strcpy(secondLongestWord, longestWord);
strcpy(longestWord, token);
} else if (wordLength > secondLongestLength) {
// 如果当前单词比第二长的单词长
secondLongestLength = wordLength;
strcpy(secondLongestWord, token);
}
token = strtok(NULL, " ");
}
}
这个程序通过 getLongestWords
函数来实现获取最长单词和第二长单词的长度。在 main
函数中,首先将逗号和句号替换为空格,然后调用 getLongestWords
函数来获取最长单词和第二长单词的长度。最后打印结果。
请注意,程序只支持用空格分隔的英语句子输入,并且不包含数字以及除逗号和句号意外的其他标点符号。如需处理其他情况,可以根据需要进行适当修改。
int main()
{
char ch;
int fst = 0, snd = 0, i = 0;
while (ch = getchar())
{
if (ch == ',' || ch == '.' || ch == '\n')
{
if (i > fst)
{
snd = fst;
fst = i;
}
else if (i > snd && i < fst)
snd = i;
i = 0;
}
else
{
i++;
}
if (ch == '\n')
break;
}
printf("%d %d\n", fst, snd);
return 0;
}
【相关推荐】
链接:https://www.jianshu.com/p/4f9202e11991