統計程序輸入中各個數字、空白符和其他字符出現的次數

1、if-else語句C實現

#include <stdio.h>
/* count digits, white space, others */

main()
{
    int c, nwhite, nother;
    int ndigit[10];
    nwhite = nother = 0;
    
    for(int i = 0; i < 10; ++i)
        ndigit[i] = 0;

    while ((c = getchar()) != EOF)
    {
        if(c >= '0' && c <= '9')
            ++ndigit[c-'0'];
        else if (c == ' ' || c == '\n' || c == '\t')
            ++nwhite;
        else
            ++nother;
    }
    
    printf("digits =");
    for (int i = 0; i < 10; ++i)
        printf(" %d", ndigit[i]);
    
    printf(", white space = %d, other = %d\n",nwhite

2、case語句C實現

#include <stdio.h>

int main(void) { 
    
int c, nwhite, nother, ndigit[10]; //nwhite統計空白字符數、nother統計其他字符數、ndigit數組統計1-9數字出現的次數

nwhite = nother = 0;

for (int i = 0; i < 10; i++) //初始化存放統計數字出現次數的數組
    ndigit[i] = 0;

while ((c = getchar()) != EOF) {
switch (c) {
    case '0': 
    case '1':
    case '2': 
    case '3': 
    case '4':
    case '5': 
    case '6': 
    case '7': 
    case '8': 
    case '9':
        ndigit[c-'0']++;
        break;
    
    case ' ':
    case '\n':
    case '\t':
        nwhite++;
        break;

    default:
        nother++;
        break;
    }
}

printf("digits =");
for(i = 0; i < 10; i++)
printf(" %d", ndigit[i]);

printf(", white space = %d, other = %d\n",nwhite, nother);

return 0;

}

 

 

程序源碼分別來源於《C語言程序設計》1.6節和3.4節。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章