Unlike the other answer, you don’t need to sort characters or anything like that.
Just scroll through the characters and go computing the totals. And how one char
in C always has 1 byte (and therefore there are 256 possible values), you can create an array with 256 positions, and go saving the totals of each character in it:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char *str = malloc(1024);
if (str == NULL) {
printf("Erro ao alocar memória\n");
exit(EXIT_FAILURE);
}
printf("digite a frase:");
if (fgets(str, 1024, stdin) == NULL) {
printf("Erro ao ler dados\n");
exit(EXIT_FAILURE);
}
int counts[256] = { 0 };
// percorre a string, atualizando a contagem de cada caractere
for (char *ptr = str; *ptr != '\0' && *ptr != '\n'; ptr++) {
if (*ptr != ' ') // entendi que não conta os espaços
counts[(unsigned char) *ptr]++;
}
// mostra os totais que forem maiores que zero
for (int i = 0; i < 256; i++) {
if (counts[i] != 0)
printf("%c = %d\n", i, counts[i]);
}
free(str);
return 0;
}
Also be sure to allocate space for the string before calling fgets
- the other answer did not do this, and if it worked, it is by coincidence, therefore call fgets
without allocating memory before has undefined behavior and it’s not guaranteed that it always works - so much so that I tested it without allocating memory and it didn’t work (see the difference here and here).
Anyway, I made one for
checking that the character is not the null Terminator or the \n
- for fgets
adds the \n
, except if you type more characters than indicated by the second parameter (because in this case you will not have the \n
).
Of course, if you’re going to use this string later and you don’t want the \n
, then it’s worth doing what was done in the other answer. But if you just want to count the characters and nothing else, I think it’s simpler to do a single loop and stop when you find the \n
or the \0
.
In this loop I’ll update the count of each character, taking advantage of the fact that in fact char
are bytes and can be interpreted as numbers (and therefore I can use them as array indices counts
). I didn’t count the spaces, which seems to be what you wanted (but if so, just change the if
within the for
, to choose which characters will be counted).
This is more efficient by going through the string only once. I saw no need to sort it (and even more so using a quadratic algorithm), and on top of that strlen
is called several times, which makes everything even more inefficient.
One possibility is you sort the characters of your string and go counting the repetitions. I didn’t see in your table the space counter, it’s not to count?
– anonimo