Advertisement
eXFq7GJ1cC

Untitled

Aug 19th, 2012
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.94 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. typedef struct { char c; unsigned count; } charcount_t;
  6.  
  7. charcount_t *count_chars(char *s)
  8. {
  9.     charcount_t *counts = calloc(256, sizeof(charcount_t));
  10.     for(int i = 0; i < 256; i++)
  11.         counts[i].c = i;
  12.  
  13.     while(*s)
  14.         counts[(unsigned)*s++].count++;
  15.  
  16.     return counts;
  17. }
  18.  
  19. int int_pair_desc(const void *a, const void *b)
  20. {
  21.     return ((charcount_t *)b)->count - ((charcount_t *)a)->count;
  22. }
  23.  
  24. int main()
  25. {
  26.     char msg[] = "I am a large brown bear who lives in the forest.  My diet consists primarily of honey and spaceships.";
  27.     printf("string: '%s'\n", msg);
  28.     charcount_t *counts = count_chars(msg);
  29.     qsort(counts, 256, sizeof(charcount_t), int_pair_desc);
  30.     for(int i = 0; i < 256; i++)
  31.         if(counts[i].count > 0)
  32.             printf("Rank[%d]: '%c' - %u\n", i + 1, counts[i].c, counts[i].count);
  33.    
  34.     free(counts);
  35.     return 0;
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement