wangfen的宝子 2023-09-22 23:09 采纳率: 93.8%
浏览 5
已结题

求一个刚学c语音的人能看懂的代码

编写程序,统计一个英文句子中最长的单词和第二长的字符数。
程序设计要求:
(1)必须支持用有逗号和句号的英语句子来输入。
(2)两个长度不能相同,比如输入的单词长度为4,4,4,3,3,2,则需要输出4和3而不是4和4。
(2)输入的英语句子无需包含数字以及除逗号和句号意外的其他标点符号。

  • 写回答

2条回答

  • Lucky_Dog_c 2023-09-22 23:15
    关注

    下面是使用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函数来查找最长单词和第二长单词,并输出结果。

    请这个程序假设输入的英文句子中只包含字母、空格、逗号和句号,不包含数字以及其他标点符号。如果输入的句子包含其他字符,程序可能无法正确处理。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月31日
  • 已采纳回答 10月23日
  • 创建了问题 9月22日