Never use gets
. Use fgets
. I’ll explain more about that here and here.
Your approach is wrong. To find the most frequent letter, use a table (with an array) to compute these letters.
Remember that char
occupies only one byte of memory. This means that the table has 256 numbered positions from 0 to 255.
The function strlen
is slow, as it traverses the string to the end of it to find out the size. By using it as the stop condition of the for
, it will be fully traversed in each iteration. The solution is to use strlen
only once and save the result in a variable.
Soon:
#include <stdio.h>
#include <stdlib.h>
int main() {
char string[100];
char tabela[256];
// Limpa a tabela.
for (int i = 0; i < 256; i++) {
tabela[i] = 0;
}
// Lê a frase do usuário.
printf ("\nEscreva um texto: \n");
fgets(string, 100, stdin);
int tamanho = strlen(string);
// Monta a tabela de frequências.
for (int i = 0; i < tamanho; i++) {
tabela[string[i]]++;
}
// Busca o índice de maior ocorrência na tabela.
int maior = 0;
char letra = '\0';
for (int i = 0; i < 256; i++) {
int t = tabela[i];
if (t > maior) {
maior = t;
letra = (char) i;
}
}
// Mostra o resultado.
printf("\nO caractere '%c' aparece %d vezes.\n", letra, maior);
// Fim.
return 0;
}
With that input:
oRatoRoeuARoupaDoReiDeRomaEARainhaRoeuOResto.
It generates this result:
O caractere 'R' aparece 8 vezes.
See here working on ideone.
There is a catch yet. If I use this entry:
O rato roeu a roupa do rei de Roma e a rainha roeu o resto.
The character that occurs most often is white space. This is probably not what you want. It also happens that r
(minuscule) and R
(uppercase) are different characters. To solve this, you can change the for
that mounts the table for this:
// Monta a tabela de frequências.
for (int i = 0; i < tamanho; i++) {
char c = string[i];
// Ignora o espaço.
if (c == ' ') continue;
// Se for uma letra minúscula, troca por maiúscula.
if (c >= 'a' && c <= 'z') c = c - 'a' + 'A';
// Contabiliza na tabela.
tabela[c]++;
}
With that input:
O rato roeu a roupa do rei de Roma e a rainha roeu o resto.
It generates this result:
O caractere 'O' aparece 9 vezes.
See here working on ideone.
You can create variables that store the amount of the most repeated character and the character itself; in the loop, you check whether
cont
is greater than the current maximum amount and, if so, updates the value and character; at the end of the program, simply display them.– Woss
Mount an array of integers with a position for each letter. Initialize all positions with zero. Traverse the string with a
for
and at each iteration, increment the corresponding position of the array. At the end, just look for the most accessed position of the array. Beware of symbols that are not letters such as blank space, comma and period. And do not usegets(string)
, usefgets(string, 100, stdin)
.– Victor Stafusa