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

Posted on

#### Question :

I need to count the relative frequency of each letter in a string (letters only), without considering spaces, not case-sensitive and without differentiating accented letters. I was able to create a code that does more or less that, but the program repeats the counts unnecessarily. For example, in the phrase “Oh my God,” the program prints “The letter a appears 3 times” three times when it should print once. How can I correct that? And do I just count 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;
}
}
``````

Note that your% of_with% that is within the% of external%, runs once for each letter of `if` , regardless of whether this letter has already been counted 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 `for` or `String` and check if the new letter is already there.

If you want to put in a variable `StringBuilder` (let’s suppose you call `String` ), your `String` would look like this:

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

EDIT: Set `jaEncontrados` within second `if` . It will become `v = v + s.charAt(j);` .

Much easier:

``````len('Ai minha cuca') - len(replace('Ai minha cuca','a','')
``````