Count the number of occurrences of each letter in string

前端 未结 15 2022
别跟我提以往
别跟我提以往 2020-12-10 20:02

How can I count the number of occurrences in c of each letter (ignoring case) in the string? So that it would print out letter: # number of occurences, I have c

15条回答
  •  难免孤独
    2020-12-10 20:46

    #include
    #include
    
    #define filename "somefile.txt"
    
    int main()
    {
        FILE *fp;
        int count[26] = {0}, i, c;  
        char ch;
        char alpha[27] = "abcdefghijklmnopqrstuwxyz";
        fp = fopen(filename,"r");
        if(fp == NULL)
            printf("file not found\n");
        while( (ch = fgetc(fp)) != EOF) {
            c = 0;
            while(alpha[c] != '\0') {
    
                if(alpha[c] == ch) {
                    count[c]++; 
                }
                c++;
            }
        }
        for(i = 0; i<26;i++) {
            printf("character %c occured %d number of times\n",alpha[i], count[i]);
        }
        return 0;
    }
    

提交回复
热议问题