首页 > 解决方案 > C程序检查句子是否是一个pangram(包含字母中所有字母的句子)

问题描述

我需要从用户那里得到 10 个单词,然后判断他输入的句子是否是 pangram。而且我的代码不像我期望的那样工作。我没有发现问题是如果有人能告诉我问题是我真的很感激 pangram 的例子:“快速棕色狐狸跳过懒狗”“Glib jocks quiz nymph to vex dwarf”,这是我的代码

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

#define MAX_NAMES 10
#define LONG 50

int main()
{
    char names[MAX_NAMES][LONG] = {0};
    bool flage = true;
    int i = 0, j = 0, k = 0;
    char allAlphabet[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
    int countAlfa = 0;
    
    printf("Enter up to 10 words, try to make a pangram:\n");
    for(i = 0; (i < MAX_NAMES) && (flage == true); i++)
    {
        fgets(names[i], LONG, stdin);
        names[i][strcspn(names[i], "\n")] = 0;
        for(j = 0; (k < strlen(names[i])) && (j < strlen(allAlphabet)); j++)
        {
            if(names[i][k] == allAlphabet[j])
            {
                countAlfa++;
                allAlphabet[j] = '#';
                k++;
                j = 0;
            }
        }
        k = 0;
        if(countAlfa > 25)
        {
            printf("It's a pangram?\n");
            printf("Yes\n");
            flage = false;
        }
    }
    if(countAlfa < 26)
    {
        printf("It's a pangram?\n");
        printf("No\n");
    }
}


标签: c

解决方案


正如 Jonathan Leffler 所指出的,有一种更好的方法可以做到这一点,即使用一个由 26 个计数器组成的数组,初始化为全零。
然后,当您浏览字母时,您会增加相应的计数器,可以使用字符值轻松访问。

这是一个小的概念证明。我假设名称总是有 N+1 个元素,最后有一个 NULL 指针

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define FALSE (0 != 0)
#define TRUE  (!FALSE)

#define MAX_NAMES 10
#define LONG 50

int main()
{
    char names[MAX_NAMES][LONG] = { "The", "quick", "brown", "Fox", "jumps", "over", "the", "lazy", "Dog" };
    char flag = TRUE;
    int i = 0, j = 0;
    char allAlphabet['z' - 'a' + 1] = {0}; // The size is constant and calculated at compile time
    
    while (*names[i] != 0)
    {
        for (j = 0; j < strlen(names[i]); j++)
        {
            int letter = tolower(names[i][j]);
            if (letter >= 'a' && letter <= 'z')
                allAlphabet[letter - 'a']++; // The letter is used to access the counter
        }
        i++;
    }
    
    for (i = 0; i < sizeof(allAlphabet); i++)
    {
        if (allAlphabet[i] == 0)
        {
            printf("%c is missing\n", i + 'A');
            flag = FALSE;
            break;
        }
    }
    
    printf("It's a pangram?\n%s\n", flag ? "Yes" : "No");
}

编辑:我在上次检查中使用了反转逻辑。我喜欢它,但它让事情变得更难理解。感谢 Roberto Caboni 指出这一点

https://www.jdoodle.com/iembed/v0/91G


推荐阅读