How do I check if two strings are anagrams of each other?

Asked

Viewed 6,555 times

5

I need to buy two strings and check if the second one is an anagram of the first one. I thought I’d use FOR repeat loops. I think you should first check if both are the same size, then go through them and check if each letter of the first one exists also in the second one. If they all exist, one is the other’s anagram. I just don’t 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...
                }
            }
        }
    }
  • 2

    An alternative way to do it is to sort the letters of each word in alphabetical sequence and check if they are equal.

  • I noticed that during the acceptance you first accepted my answer and then Victor’s. I don’t know if you know that acceptance, unlike the vote, can only be made for one answer in each question. And acceptance is the last one you click. I don’t know if your intention was to actually choose Victor’s answer, which is a good answer, I would have no problem accepting it, or choosing mine. No matter which one you choose, the decision is yours, but it is important to understand how the tool works and make a choice according to your real will.

  • @bigown This happened because I first saw your answer and I already accepted it, then I saw Victor’s and I thought she was more suited to the style of programming that I use. Your solution is good too (if I could, I would keep the vote on both, even because they are very similar), but it uses modularization, which I still do not understand very well nor know how to use right. Anyway, thank you for your help and for worrying about explaining about the working of the tool :)

2 answers

6


I think of three ways to do that.

The first way is to count the frequency of each character for each String and then compare 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");
    }

4

I found that response in the OS 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);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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