2016-08-02 61 views
3

我想要一個代碼來計算陣列中字母的出現次數。我已經查看了確切的各種代碼,但他們都使用字符串。我的問題在於嚴格使用陣列。 我創建了一個代碼,但它返回:: 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; 

} 
+0

凡你覺得你寫的每一個計數的炭量的代碼?.... – LPs

+2

大加提供例如輸入預計輸出!目前它並不流行:p – xenteros

+1

+1,正確測試eof。許多更有經驗的程序員不理解並正確使用它。讓我相信你會弄清楚計數和東西;-)。 –

回答

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')這使得輸入的字符0的索引值。
  2. 您必須檢查輸入的字符是字母字符。 if (isalpha(c))這樣做。
  3. 打印輸出必須使用的陣列和陣列內容的索引打印字符
+0

@Downvoter:任何建議..?o.O – LPs

+0

由於'for'循環從'i = 0'開始,所以不需要初始化'int i = 0;'。 – kvk30

+0

@ kvk30 Weel,希望這不是downvote的原因;)BTW不是一個錯誤/問題。它是從OP代碼粘貼的,但我仍然會這樣做,以避免今後的局部範圍變量出現bug。 – LPs

-1

我可以建議你做這樣的事情:

while (c != EOF) { 

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

要生成正確的索引每個CHAR你可以使用函數:

// 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; 
} 
+3

正確。你應該添加'printf(「%c:%d」,'A'+ i,計數[i]);'完成答案。 – LPs

+1

重新讀取您的代碼是UB,由於'c'值是> 26' ... – LPs

+0

是的,c必須小於26,這就是爲什麼我寫道「我不知道你使用什麼編碼,也許你還應該在使用之前減少c「。我剛剛發佈了基本算法。 –