Two strings are said to be anagram if they contain same set of characters but in different order. For example, "Mother In Law" and "Hitler Woman" are anagrams.
import java.util.Arrays;
public class Anagram
{
public void isAnagram(String str1, String str2)
{
//Removing all white spaces from Strings
String newStr1 = str1.replaceAll("\\s", "");
String newStr2 = str2.replaceAll("\\s", "");
//Set initial status to true
boolean status = true;
if(newStr1.length() != newStr2.length())
{
//Setting status as false if newStr1 and newStr2 doesn't have same length
status = false;
}
else
{
//Change the case of characters of both newStr1 and newStr2 and convert them to char array
char[] str1Array = newStr1.toLowerCase().toCharArray();
char[] str2Array = newStr2.toLowerCase().toCharArray();
//Sort both str1Array and str2Array
Arrays.sort(str1Array);
Arrays.sort(str2Array);
//Check whether str1Array and str2Array are equal
status = Arrays.equals(str1Array, str2Array);
}
//Display if Strings are Anagrams or not
if(status)
{
System.out.println(str1+" and "+str2+" are Anagrams.");
}
else
{
System.out.println(str1+" and "+str2+" are not Anagrams.");
}
}
public static void main(String[] args)
{
Anagram an = new Anagram();
an.isAnagram("School MASTER", "The ClassROOM");
an.isAnagram("ASTRONOMERS", "NO MORE STARS");
an.isAnagram("joy", "enjoy");
}
}
Comments