计算数组中出现的字母数

时间:2016-08-02 07:34:42

标签: c arrays

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

一个正确的例子: 的输入

The quick brown fox jumps over the lazy dog.

输出

A: 1
B: 1
C: 1
D: 1
E: 3
F: 1 ...

以下是我的代码:

#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;

}

2 个答案:

答案 0 :(得分: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;
}
  1. 您的数组旨在存储每个字母的出现次数。所以数组的idex必须是后者输入的。正如您所看到的,我使用(toupper(c)-'A')来创建基于输入char 0的索引的值。
  2. 您必须检查输入的char是否为字母字符。 if (isalpha(c))这样做。
  3. 打印输出必须使用数组索引和数组内容打印字符

答案 1 :(得分:-1)

我可以建议你做那样的事情:

while (c != EOF) {

     counts[charToIndex(c)] ++;
     c = getchar();           
}

要为每个字符生成正确的索引,您可以使用函数:

// This function should return values from 0 to sizeof(counts)/sizeof(char)
int charToIndex(char c) {

    //For example, you can check each possible value of c
    if (c == 'a' || c == 'A') {

        return 0;  
    }
    if (c == 'b' || c == 'B') {

        return 1;  
    }        
    // And so on ...
    return 0;
}
相关问题