Question:
How to test if two words are anagram using Arrays.sort()?
Code:
import java.util.Scanner; public class Anagram { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter first word: "); String word1 = sc.nextLine(); System.out.print("Enter second word: "); String word2 = sc.nextLine(); System.out.println("Anagram: " + isAnagram(word1,word2)); } // Test if two words are Anagram using Character Array public static boolean isAnagram(String word1, String word2) { word1 = word1.toLowerCase(); word2 = word2.toLowerCase(); if (word1.length() != word2.length()) { return false; } char[] chars = word1.toCharArray(); for (char c : chars) { int index = word2.indexOf(c); if (index != -1) { word2 = word2.substring(0, index) + word2.substring(index + 1, word2.length()); } else { return false; } } return word2.isEmpty(); } }
Output:
$ java Anagram Enter first word: Star Enter second word: rats Anagram: true $ java Anagram Enter first word: rate Enter second word: tree Anagram: false