You don’t have to make a loop within another, for this is very inefficient: for each character of the String
, you want to compare it to each of the 26 letters, then at the end you will be doing N * 26 iterations (being N
the size of String
).
You can do all this by going through String
a single time. Simply create an array containing the count of each letter, and update it as you go through the String
.
Then you make another loop to show the quantities of each letter:
String frase = "Daniel Henrique";
int[] quantidades = new int[26];
for (char c : frase.toUpperCase().toCharArray()) {
int indice = c - 65;
if (indice >= 0 && indice < 26) {
quantidades[indice] += 1;
}
}
for (int i = 0; i < quantidades.length; i++) {
char letra = (char) (i + 65);
System.out.println(letra + "=" + quantidades[i]);
}
First I create an array containing the quantities of each letter, so it has 26 positions. I take advantage of the fact that in Java, an array of int
created this way is already initialized with zero at all positions (which is just what we need, because at the beginning the amount of any letter is zero, since I haven’t started counting).
In the first for
I go through the String
. Your code implied that it doesn’t matter if the letters are uppercase or lowercase, so I’m capitalizing (toUpperCase()
).
For each character, I check if it is a letter of A
to Z
(by subtracting 65 from a char
, if this is a letter from A
to Z
, the result will be between zero and 25, which is a valid position in the quantity array). If it is, I add 1 in the respective quantity.
In the second for
i print the letters and their respective quantities. In the end, I just went through the String
and quantities once, totalling N + 26 iterations (being N
the size of String
) - much better than making a loop within another, which as already said, generates N * 26 iterations.
These two checks (from 65 to 90 && 97 to 122) is to check the right uppercase and lowercase?
– Daniel Henrique