计算数组中出现的字母数

Moh*_*d H 3 c arrays

我想要一个计算数组中字母出现次数的代码.我已经查看了各种准确的代码,但它们都使用字符串.我的问题是严格使用数组.我创建了一个代码,但它返回:: 0 : 1 : 2 : 3 : 4 : 5 : 6 : 7 : ...

一个正确的例子: 输入:

The quick brown fox jumps over the lazy dog.
Run Code Online (Sandbox Code Playgroud)

输出:

A: 1
B: 1
C: 1
D: 1
E: 3
F: 1 ...
Run Code Online (Sandbox Code Playgroud)

以下是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
    int i = 0;
    int c;
    char counts[26] = {0};  

    c = getchar();              


    while (c != EOF && i < 26) {
        counts[i] = c;
        i += 1;
        c = getchar();           
    }

    for (i = 0; i < 26; i++) {

        if (counts[i] !=0 ) 
        printf("%c: %d", toupper(c), i);
    }


    return EXIT_SUCCESS;

}
Run Code Online (Sandbox Code Playgroud)

LPs*_*LPs 10

使用你的代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(void)
{
    int c;
    int counts['Z' - 'A'] = {0};
    c = getchar();
    while (c != EOF) 
    {
         if (isalpha(c))
            counts[(toupper(c)-'A')]++;
         c = getchar();
    }

    for (unsigned int i = 0; i < sizeof(counts)/sizeof(counts[0]); i++) 
    {    
        if (counts[i] !=0 )
            printf("%c: %d\n", 'A'+i, counts[i]);
    }

    return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
  1. 您的数组旨在存储每个字母的出现次数.所以数组的idex必须是后者输入的.正如您所看到的,我使用(toupper(c)-'A')了使得输入char 0的索引值.
  2. 您必须检查输入的char是否为字母char.if (isalpha(c))去做.
  3. 打印输出必须使用数组索引和数组内容打印字符