Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- typedef struct { char c; unsigned count; } charcount_t;
- charcount_t *count_chars(char *s)
- {
- charcount_t *counts = calloc(256, sizeof(charcount_t));
- for(int i = 0; i < 256; i++)
- counts[i].c = i;
- while(*s)
- counts[(unsigned)*s++].count++;
- return counts;
- }
- int int_pair_desc(const void *a, const void *b)
- {
- return ((charcount_t *)b)->count - ((charcount_t *)a)->count;
- }
- int main()
- {
- char msg[] = "I am a large brown bear who lives in the forest. My diet consists primarily of honey and spaceships.";
- printf("string: '%s'\n", msg);
- charcount_t *counts = count_chars(msg);
- qsort(counts, 256, sizeof(charcount_t), int_pair_desc);
- for(int i = 0; i < 256; i++)
- if(counts[i].count > 0)
- printf("Rank[%d]: '%c' - %u\n", i + 1, counts[i].c, counts[i].count);
- free(counts);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement