How do I check if two strings are anagrams of one another?

5

I need to buy two strings and check if the second is an anagram of the first. I thought about using FOR loop repetition. I think you should first check if they both have the same size, then go through them and check if each letter of the first one also exists in the second. If they all exist, one is the anagram of the other. I just do not know how to do this ...

public static void main(String[] args) {
        Scanner ent = new Scanner(System.in);
        String s, r;
        int i, j;
        System.out.println("Digite a palavra/frase:");
        // crio as strings
        s = ent.nextLine();
        r = ent.nextLine();
        // verifico se têm o mesmo tamanho
        if (s.length()==r.length()) {
            // percorro ambas verificando se cada letra da 1ª existe na 2ª
            for (i=0; i<s.length(); i++) {
                for (j=0; j<r.length(); j++) {
                // não sei continuar...
                }
            }
        }
    }
    
asked by anonymous 29.11.2014 / 02:52

2 answers

5

I think of three ways to do this.

The first way is to count the frequency of each character for each String and then compare the frequencies.

The second way is to sort the letters of both Strings and see if the result matches.

The third way is to use Java functions already ready for this:

    s = ent.nextLine();
    r = ent.nextLine();
    char[] a = s.toCharArray();
    char[] b = r.toCharArray();
    Arrays.sort(a);
    Arrays.sort(b);
    if (Arrays.equals(a, b)) {
        System.out.println("Anagrama");
    } else {
        System.out.println("Não é anagrama");
    }
    
29.11.2014 / 02:58
4

I found this answer in the SO which is what you need:

public static boolean isAnagram(String s1, String s2) {
    //se as duas strings não tem o mesmo tamanho, não é anagrama
    if ( s1.length() != s2.length() ) {
        return false;
    }
    //tranfroma em arrays para poder ordenar
    char[] c1 = s1.toCharArray();
    char[] c2 = s2.toCharArray();
    //ordena para garantir a comparação simplificada
    Arrays.sort(c1);
    Arrays.sort(c2);
    //cria as novas strings baseadas nos arrays ordenados
    String sc1 = new String(c1);
    String sc2 = new String(c2);
    return sc1.equals(sc2);
}

See running on ideone . And in Coding Ground . Also I placed in GitHub for future reference .

    
29.11.2014 / 02:57