Code:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
void countOccurrences(char* str)
{
// 1) Count occurrences.
int occurrences[256] = {0};
for(; *str; str++)
occurrences[(unsigned char) *str]++;
// 2) Print occurences.
for(size_t i = 0; i < 256; i++)
if(occurrences[i])
printf("'%c' occurs %d times\n", (char) i, occurrences[i]);
}
int main()
{
countOccurrences("Hello World");
return 0;
}
Code:
' ' occurs 1 times
'H' occurs 1 times
'W' occurs 1 times
'd' occurs 1 times
'e' occurs 1 times
'l' occurs 3 times
'o' occurs 2 times
'r' occurs 1 times
This counts and prints the unique occurrences of each char in str, which is probably what you wanted? Notice that the entire string needs to be in memory for this to work, which is more than is strictly necessary for your situation. Another implementation would be:
Code:
int main()
{
// 1) Count occurrences.
int c, occurrences[256] = {0};
while((c = fgetc(stdin)) != EOF)
occurrences[(unsigned char) c]++;
// 2) Print occurrences.
for(size_t i = 0; i < 256; i++)
if(occurrences[i])
printf("'%c' occurs %d times\n", (char) i, occurrences[i]);
return 0;
}