Count number of occurrences of each character in input
I want to count the number of occurrences of each character found in the input and print it to the output.
Code:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv)
{
unsigned int countChars = 0, i = 0, k = 0;
char c, s[100], str[100];
str[k] = '\0';
while((c = fgetc(stdin)) != EOF)
{
s[i++] = c;
countChars++;
}
// printf("%s\n", s);
for(int i = 0; i < strlen(s); i++)
{
unsigned int countOccurrences = 1;
for(int j = i+1; j <= strlen(s); j++)
{
if(s[i]==s[j])
{
countOccurrences++;
}
/*if(strchr(str, s[i]) == NULL)
{
str[k] = s[i];
k++;
}
}
for(k = 0; k < strlen(str); k++)
{
fprintf(stdout, "The character %c has %u occurrences.\n", str[k], countOccurrences);
}*/
}
fprintf(stdout, "The character %c has %u occurrences.\n", s[i], countOccurrences);
}
return 0;
}
So far for the input:
john eats apples
Output
The character j has 1 occurrences.
The character o has 1 occurrences.
The character h has 1 occurrences.
The character n has 1 occurrences.
The character has 2 occurrences.
The character e has 2 occurrences.
The character a has 2 occurrences.
The character t has 1 occurrences.
The character s has 2 occurrences.
The character has 1 occurrences.
The character a has 1 occurrences.
The character p has 2 occurrences.
The character p has 1 occurrences.
The character l has 1 occurrences.
The character e has 1 occurrences.
The character s has 1 occurrences.
The character
has 1 occurrences.
The character has 1 occurrences.
So I need to add the characters in an array an check that each character appears only once in the array. I tried doing that with strchr and but only garbage was printed. Any ideas?