Two strings are called anagrams if they contain same set of characters but in different order. For example: "keep – peek", "School Master – The Classroom" are some anagrams.
package testjava.javatest;
public class AnagramStringBuilder
{
static void isAnagram(String mystr1, String mystr2)
{
//Removing white spaces from s1 and s2 and converting case to lower
String str1 = mystr1.replaceAll("\\s", "").toLowerCase();
String str2 = mystr2.replaceAll("\\s", "").toLowerCase();
//Initially setting status as true
boolean status = true;
if(str1.length() != str2.length())
{
//Setting status as false if str1 and str2 doesn't have same length
status = false;
}
else
{
//Converting str1 to char array
char[] str1Array = str1.toCharArray();
//Constructing StringBuilder from str2
StringBuilder sb = new StringBuilder(str2);
//Checking whether each character of str1Array is present in sb
for (char ch : str1Array)
{
int index = sb.indexOf(""+ch);
if (index != -1)
{
//If character present, removing that character from sb
sb = sb.deleteCharAt(index);
}
else
{
//If not present, setting status as false and breaking the loop
status = false;
break;
}
}
}
if(status)
{
System.out.println(mystr1+" and "+mystr2+" are anagrams");
}
else
{
System.out.println(mystr1+" and "+mystr2+" are not anagrams");
}
}
public static void main(String[] args)
{
isAnagram("Programs Buzz", "Buzz Programs");
isAnagram("keEp", "peeK");
isAnagram("Debit Card", "Bad Credit");
isAnagram("Toss", "Boss");
isAnagram("one", "none");
}
}
Programs Buzz and Buzz Programs are anagrams
keEp and peeK are anagrams
Debit Card and Bad Credit are anagrams
Toss and Boss are not anagrams
one and none are not anagrams