利用数组统计各字符出现次数

貌似没什么难的
不想解释了
算了,疏通下逻辑把
定义整形变量 c , i , nwhite,nother
再定义长度位10的整型数组ndigit[10]
那个for是将数组的值都初始化为0了
下面是循环体的执行,条件依旧是那个,已经讲过
那个
if (c >= '0' && c <= '9')
    ++ndigit[c - '0'];
可以自己单独执行,会发现这里是,如果你输入的是9,那么第ndigit[9]个就+1,以此类推
到了else if那里,执行从左到右,只要有一个为真,立马执行,比如你输入9,那么nwhite会+1
因为getchar()吸收了一个 ,如若你输入的是‘9 ’,nwhite = 2,它的执行流程就是9循环一次,空格循环一次,' '再循环一次
最后将数组打印出来,这又是有点类似于标志寄存器的思想了
int main()
{
        int c, i, nwhite, nother;
        int ndigit[10];
        nwhite = nother = 0;
        for (i = 0; i < 10; ++i)
               ndigit[i] = 0;
        while ((c=getchar()) != EOF)
        {
               if (c >= '0' && c <= '9')
                       ++ndigit[c - '0'];
               else if (c == ' ' || c == ' ' || c == ' ')
                       ++nwhite;
               else
                       ++nother;
        }
        printf("digits = ");
        for (i = 0; i < 10; ++i)
               printf(" %d", ndigit[i]);
        printf(" , white space = %d, other = %d ", nwhite, nother);
        system("pause");
        return 0;
}
 
原文地址:https://www.cnblogs.com/EvilAnne/p/9435216.html