Compare chars between Strings

0

I would like to know how to compare the chars of the strings to know how many chars coincide regardless of their position. I'm doing this but it's out of my hands, I do not get the length I should.

        /* Panel mostrará los caracteres de "frase" que coincidan con   
        "intentos". Los que no coincidan los mostrará con un guion:"-" */                 
        String panel = "";

        String intentos = "String intentos";
        String frase = "Esto es una frase";

        for (int i = 0; i < frase.length(); i++)
        {
            for (int j = 0; j < frase.length(); j++)
            {
                if (j!=i && intentos.charAt(j) == frase.charAt(i))
                {
                    panel+=frase.charAt(i);
                }
                else 
                {
                    panel+="-";
                }
            }
        }
    
asked by AlejandroB 12.06.2018 в 01:01
source

1 answer

1

One way to do this would be to use an array of characters, which is initially filled with hyphens, and only if one of the attempt letters matches one of the sentences is it replaced at the position it is in.

I also corrected an error in the cycles so that the two traveled up to the sentence length, causing at some point to try to find characters outside the length of attempts.

    String intentos = "String intentos";
    String frase = "Esto es una frase";
    char panel[] = new char[frase.length()];
    for (int i = 0; i < frase.length(); i++) {
        panel[i] = '-';
    }

    for (int i = 0; i < frase.length(); i++) {
        for (int j = 0; j < intentos.length(); j++) {
            if (intentos.toLowerCase().charAt(j) == frase.toLowerCase().charAt(i)) {
                panel[i] = frase.charAt(i);
            }
        }
    }
    for (int i = 0; i < panel.length; i++) {
        System.out.print(panel[i]);
    }

    
answered by 12.06.2018 / 03:42
source