Your solution is close to working. You just need to consider occurrences with more than 1
and disregard letters that have already been processed. There are many possibilities for solving the letters already processed, and one of them would be to save% as well as the ones that have already left and do not consider them.
Keeping your original logic and making these adjustments would look like this:
char Char;
int count;
String s = "Par programming is fun!";
s = s.toLowerCase();
String carateresSaidos = ""; //para manter registo das letras que ja sairam
for (Char = 0; Char <= s.length()-1; Char++) {
count = 0;
if (carateresSaidos.indexOf(s.charAt(Char)) == -1){ //se ainda não saiu
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == s.charAt(Char)) {
count++;
}
}
if (count > 1){ //mostra apenas se é repetida, ou seja, se há mais que uma
System.out.println("Number of occurences of "+s.charAt(Char) + " is " + count);
}
carateresSaidos += s.charAt(Char); //adicionar esta letra as que já sairam
}
}
Example on Ideone
However, there are far more performative solutions, which do not imply using two String
(which is a quadratic solution). I show a solution, similar to the last @Felipe solution, but using a native array to count the various letters. This solution assumes that for
contains only ASCII characters.
int[] contagens = new int[256];
for (int i = 0; i < s.length(); ++i)
contagens[s.charAt(i)]++;
for (int i = 0; i < 256; ++i){
if(contagens[i] > 1){
System.out.println("Number of occurences of " + (char)i + " is " + contagens[i]);
}
}
See this solution also in Ideone
The first String
passes on each letter and increases for
to the corresponding position in the array. The position will match the letter number in the ASCII table. The second 1
only shows the counts that were left with more than for
.