Find the most frequent character in a text

Asked

Viewed 203 times

0

I did so, but I would like printf did not keep repeating... There is some way to display only the most frequent character?

#include <stdio.h>
#include <stdlib.h>

int main()
{
  char string[100];
  char letras[] = "abcdefghijklmnopqrstuvxzwyABCDEFGHIJKLMNOPQRSTUVXZWY";
  int n1, n2, cont=0;

    printf ("\nEscreva um texto: \n");
    gets(string);

    for (n1=0; n1<strlen(letras); n1++)
    {
        for (n2=0; n2<strlen(string); n2++)
        {
            if (string[n2] == letras[n1])
            {
                cont++;
                printf ("\nA letra %c contem %d\n", string[n2], cont);
            }
        }

        cont=0;
    }

  system("pause");
  return 0;
}
  • 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.

  • 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 use gets(string), use fgets(string, 100, stdin).

2 answers

2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]) 
{
    char texto[82];
    char *p;
    int frequencia[256]; // São 256 caracteres ASCII.
    char caractere;
    int maiorFrequencia = 0x80000000; // Inicializado com o número mais negativo possível.

    // Informa da e aguarda a entrada do texto.
    fflush(stdin);
    printf("Digite um texto:\n");
    fgets(texto, 80, stdin);

    // Inicializa frequencias.
    for (i = 0; i < 256; ++i)
    {
        frequencia[i] = 0;
    }

    // Popula frequencia com o texto digitado.
    p = texto;
    while (*p) {
        ++frequencia[*p++];
    }

    // Procura maior frequencia.
    for (i = 0; i < 256; ++i) 
    {
        if (frequencia[i] > maiorFrequencia)
        {
            maiorFrequencia = frequencia[i];
            caractere = (char)i;
        }
    }

    // Imprime caractere de maior frequencia.
    switch (caractere)
    {
        case '\n':
            strcpy(texto, "Quebra de linha");
            break;
        case ' ':
            strcpy(texto, "Espaco");
            break;
        default:
            texto[0] = '"';
            texto[1] = caractere;
            texto[2] = '"';
            texto[3] = '\0';
            break;
    }
    printf("O caractere com maior frequencia e %s, com frequencia %d\n",
        texto, maiorFrequencia);

    return 0;
}

1

  1. Never use gets. Use fgets. I’ll explain more about that here and here.

  2. Your approach is wrong. To find the most frequent letter, use a table (with an array) to compute these letters.

  3. Remember that char occupies only one byte of memory. This means that the table has 256 numbered positions from 0 to 255.

  4. 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.