Skip to content

Instantly share code, notes, and snippets.

@jrenner
Created August 19, 2012 12:42
Show Gist options
  • Save jrenner/3394648 to your computer and use it in GitHub Desktop.
Save jrenner/3394648 to your computer and use it in GitHub Desktop.
count number of chars in a string and display by rank
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int** count_chars(char *s)
{
int **counts = (int**)malloc(256 * sizeof(int) * sizeof(char));
int i;
for(i = 0; i < 256; i++)
{
counts[i] = (int*)malloc(sizeof(int)*2);
counts[i][0] = i;
counts[i][1] = 0;
}
while(*s)
{
counts[(int)*s][1] += 1;
s++;
}
return counts;
}
int int_pair_asc(const void *a, const void *b){
int *first = *(int**)a;
int *second = *(int**)b;
return first[1] - second[1];
}
int int_pair_desc(const void *a, const void *b){
return (int_pair_asc(a, b) * -1);
}
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);
int **counts = count_chars(msg);
qsort(counts, 256, sizeof(int), int_pair_desc);
int i;
for(i = 0; i < 256; i++){
if(counts[i][1] > 0)
printf("Rank[%d]: '%c' - %d\n", i+1, counts[i][0], counts[i][1]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment