Help in printing code of repeated characters

1

I want to print only the characters that are repeated in the string and the number of reps. If it only appears once, I do not want to print it. I need help with the boolean expression.

  • How do I check if the character is repeated? and
  • has already been found?

Code:

char Char;
int count;
String s = "Par programming is fun!";
s = s.toLowerCase();
for (Char = 0; Char <= s.length()-1; Char++) {
    count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.charAt(i) == s.charAt(Char) && !(s.charAt(Char)==Char)) {
            count++;
        }
    }
    System.out.println("Number of occurences of " + s.charAt(Char) + " is " + count);
}
    
asked by anonymous 03.12.2017 / 06:25

2 answers

1

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 .

    
03.12.2017 / 14:55
1

It is simpler, in this case, to turn String into array of characters. And, also, remove the characters from String that have already been checked so that they are not counted multiple times.

String text = "Par programming is fun!";
text = text.toLowerCase();
for(char c1 : text.toCharArray()) {
    int count = 0;
    for(char c2 : text.toCharArray()) {
        if(c1 == c2) {
            count++;
        }
    }
    text = text.replaceAll(String.valueOf(c1) , "");
    if(count > 1) {
        System.out.println("Number of occurences of " + c1 + " is " + count);
    }
}

Another option that does not use chained loops:

texto = texto.toLowerCase();
for(char c = texto.charAt(0); !texto.isEmpty(); c = texto.charAt(0)) {
    String temp = texto.replaceAll(String.valueOf(c), "");
    int numeroDeOcorrencias = texto.length() - temp.length();
    texto = temp;
    if(numeroDeOcorrencias > 1) {
        System.out.println("Number of occurences of " + c + " is " + numeroDeOcorrencias);
    }
    if(texto.isEmpty()) {
        break;
    }
}

A simpler solution using Java 8.

String text = "Par programming is fun!";
text.chars()
    .mapToObj(c -> Character.toLowerCase((char) c))         //Cria uma Stream como todos os chars da String
    .collect(Collectors.groupingBy(Function.identity(), 
                                    Collectors.counting())) //Conta quantas vezes cada char aparece na String
    .forEach((key, value) -> {
        //Se o char aparece mais de uma veze, ele é exibido
        if(value > 1) {
            System.out.println("Number of occurences of " + key + " is " + value);
        }
    });
    
03.12.2017 / 12:53