Count the number of occurrences of each letter in string

前端 未结 15 1994
别跟我提以往
别跟我提以往 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:33

    Here is the C code with User Defined Function:

    /* C Program to count the frequency of characters in a given String */
    
    #include 
    #include 
    
    const char letters[] = "abcdefghijklmnopqrstuvwxzy";
    
    void find_frequency(const char *string, int *count);
    
    int main() {
        char string[100];
        int count[26] = { 0 };
        int i;
    
        printf("Input a string: ");
        if (!fgets(string, sizeof string, stdin))
            return 1;
    
        find_frequency(string, count);
    
        printf("Character Counts\n");
    
        for (i = 0; i < 26; i++) {
            printf("%c\t%d\n", letters[i], count[i]);
        }
        return 0;
    }
    
    void find_frequency(const char *string, int *count) {
        int i;
        for (i = 0; string[i] != '\0'; i++) {
            p = strchr(letters, string[i]);
            if (p != NULL) {
                count[p - letters]++;
            }
        }
    }
    

提交回复
热议问题