How to count the frequency of each letter in a string?

Asked

Viewed 6,174 times

5

I need to count the relative frequency of each letter in a string (only letters), without considering the spaces, without differentiating between upper and lower case and without differentiating accented letters. I managed to create a code that does more or less that, but the program repeats the counts unnecessarily. For example, in the phrase "Oh my cuckoo", the program prints "The letter appears 3 times" three times, when it should print only once. How do I fix this? And make the program count only the letters?

Solved!

public static void main(String[] args) {
    Scanner ent = new Scanner(System.in);
    String S;
    int i, j, cont=0;
    System.out.println("Digite a palavra/frase:");
    // usuário digita string
    S = ent.nextLine();
    // a string é convertida para letras minúsculas
    // para que não haja diferenciação entre 'A' e 'a'
    String s = S.toLowerCase();
    String v = "";
    for (i=0; i<s.length(); i++) {
        for (j=0; j<s.length(); j++) {
            if (s.charAt(i)==s.charAt(j)) {
                cont++;
            } 
        }
        // ao imprimir as frequências, exclui a contagem dos espaços
        char c = s.charAt(i);
        if (c >= 'a' && c <= 'z' && !v.contains("" + c)) {
            v = v + c;
            System.out.println("A letra "+s.charAt(i)+" aparece "+cont+" vezes.");
        }
        cont=0;
    }
}

2 answers

4


Note that your if that’s inside the for external, runs once for each letter of String, no matter if this letter has been told before or not.

You will need to check whether the letter has been used before or not. One way to do this is to put the already checked letters in an array, list or StringBuilder or String and check if the new letter is already there.

If you want to put in a variable String (Let’s assume it’s called jaEncontrados), your if would look like this:

    char c = s.charAt(i);
    if (c != ' ' && !jaEncontrados.contains("" + c)) {

EDIT: Put the v = v + s.charAt(j); within the second if. Will turn into v = v + c;.

  • You can use the method contains class String, or else the method indexOf.

  • I chose to concatenate a new string, but I don’t know how to check if the new letter exists in this string. Use another FOR? Where should I put it?

  • @Cristianedossantoscosta I edited my answer. See if this solves your question. :)

  • I think it’s almost working... Which of the Ifs should I put your suggestion? I tried on the last one (I traded it for yours) and the program closes without printing anything.

  • @Cristianedossantoscosta It was on the last yes. Where you stated is String, what value you initialized it and how you are feeding it?

  • I changed the question code. See how it turned out.

  • No recommendation. the correct way to do this is with regular expression

  • @Davidschrammel I disagree with you. In this case regular expression is a cannon to kill an ant. It is an Overkill. In addition, regular expressions also perform well below that. Regular expressions are good for recognizing complex patterns and making substitutions with these patterns, not for counting occurrences. And finally, this is probably a programming exercise about basic string manipulation, and therefore regular expressions would be out of the context of the question. However, if you want to insist, post a response using regular expression and we’ll see.

  • @Victorstafusa there is no discussion, probably your code is faster, but when we put into play aspects like, legibility you lose, regular expressions were made specifically to solve problems with strings of a String,already its solution is a generic way not to say gambiarra.

Show 5 more comments

-2

Much easier:

len('Ai minha cuca') - len(replace('Ai minha cuca','a','')
  • 2

    invalid code.

  • 3

    How this code answers what was asked?

  • 2

    Luciano even understood how the example works, but I recommend that Oce guide a on the use and how it works, besides adding a clearer and less "crude" example please. Other than that, it seems like a practical example (I haven’t tested it yet, but the logic seems functional). Note that in java replace is used String a = "foo"; a.replace('o', 'i'); (to where I know at least) and to count a string we use .length()

  • 2

    It has one more detail, its code gives to understand that it will look for occurrences of a letter, what the author needs are occurrences of all characters in the string.

Browser other questions tagged

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