题目:编写函数, 再一行英文短文中找到最长的单词并求其长度, 再主函数中输出英文短文并输出结果。(短文长度不超过100, 单词长度不超过20), 短文最后以. 结尾。单词之间以, 或者空格分隔,不出现其他字符。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_ESSAY_LENGTH 100
#define MAX_WORD_LENGTH 20
void findLargestWord(const char* essay, char* largestWord, int* maxLength);
int main() {
char essay[MAX_ESSAY_LENGTH + 1];
char largestWord[MAX_WORD_LENGTH + 1];
int maxLength = 0;
printf("请输入一行英文短文(短文长度不超过100,单词长度不超过20),短文最后以. 结尾:\n");
fgets(essay, sizeof(essay), stdin);
essay[strcspn(essay, "\n")] = 0;
findLargestWord(essay, largestWord, &maxLength);
printf("原文短文: %s\n", essay);
printf("最长单词: %s\n", largestWord);
printf("最长单词长度: %d\n", maxLength);
return 0;
}
void findLargestWord(const char* essay, char* largestWord, int* maxLength) {
int currentLength = 0;
char currentWord[MAX_WORD_LENGTH + 1] = { 0 };
for (int i = 0; essay[i] != '\0'; i++) {
char c = essay[i];
if (c == ',' || c == ' ') {
if (currentLength > *maxLength) {
*maxLength = currentLength;
strcpy(largestWord, currentWord);
}
currentLength = 0;
}
else if (c == '.') {
if (currentLength > *maxLength) {
*maxLength = currentLength;
strcpy(largestWord, currentWord);
}
break;
}
else {
currentWord[currentLength++] = c;
currentWord[currentLength] = '\0';
}
}
}