This article on Anagram Program in java is to check for the two strings for Anagrams.
Let start by understanding What is Anagram?
What is Anagram?
Two strings are said to be in an anagram if they contain the same set of characters but in a different order.
For example: “Keep – peek”, “School Master – The Classroom”, “Debit Card – Bad Credit” etc.
Java Program to check whether two Strings are Anagram Or Not
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | import java.util.Arrays; public class Main { static void isAnagram(String str1, String str2) { String string1 = str1.replaceAll("\\s", ""); String string2 = str2.replaceAll("\\s", ""); boolean checkState = true; if (string1.length() != string2.length()) { checkState = false; } else { char[] ArrayStr1 = string1.toLowerCase().toCharArray(); char[] ArrayStr2 = string2.toLowerCase().toCharArray(); Arrays.sort(ArrayStr1); Arrays.sort(ArrayStr2); checkState = Arrays.equals(ArrayStr1, ArrayStr2); } if (checkState) { System.out.println(string1 + " and " + string2 + " are anagrams"); } else { System.out.println(string1 + " and " + string2 + " are not anagrams"); } } public static void main(String[] args) { isAnagram("Keep", "Peek"); isAnagram("The Classroom", "School Master"); isAnagram("Debit Card", "Bad Credit"); isAnagram("Mate", "Ate"); } } |
The output of Java Program to check whether two Strings are Anagram Or Not
Keep and Peek are anagrams
TheClassroom and SchoolMaster are anagrams
DebitCard and BadCredit are anagrams
Mate and Ate are not anagrams