Question:
How to test if two words are anagram using a StringBuilder?
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 StringBuilder public static boolean isAnagram(String word1, String word2) { word1 = word1.toLowerCase(); word2 = word2.toLowerCase(); char[] characters = word1.toCharArray(); StringBuilder sb = new StringBuilder(word2); for (char ch : characters) { int index = sb.indexOf("" + ch); if (index != -1) { sb.deleteCharAt(index); } else { return false; } } return sb.length() == 0 ? true : false; } }
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