Help in code printing of repeated characters

Asked

Viewed 151 times

1

I want to print only the characters that are repeated in string and the amount of repetitions. If it appears only once, I don’t want to print it. I need help with boolena 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);
}
  • No, use Processing which is a java subset.

2 answers

1


Your solution came 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 to solve the already processed letters, and one of them would be to store in a String apart from which have already left and do not consider these.

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 in Ideone

However, there are much more performative solutions, which do not require using two for(which is a quadratic solution). I show you a solution, equated to @Felipe’s latest solution, but using a native array to count multiple letters. This solution assumes that the String 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 for passes in each letter and increases 1 position corresponds in the array. The position will correspond to the letter number in the ASCII table. The second for just shows the scores that got more than 1.

  • 1

    I’m running out of time, but that’s what I’ve been wanting to do.

  • The first example of code is very close to what I was looking to do. Thanks for the help!

1

It’s simpler, in this case, to transform the String in a array characters. And also remove characters from String that have already been verified 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 make use of 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);
        }
    });
  • I have the impression that this will not work, read the comment above.

  • @Maniero I hadn’t noticed. I added a simpler way to check.

Browser other questions tagged

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