In this article, we will discuss and execute simple program to check whether 2 Strings are Anagrams or not
Anagrams:
- Anagrams means 2 different strings in different order but contains same characters
- Arrangement of 2 different strings which contains same characters in different order
Anagrams program steps:
- First, remove spaces in both strings
- Set flag for Anagrams
- Check length of both strings
- If length are not equal, then set flag to false
- Convert both String to char[] Array
- Sort both char[] Arrays
- Check Arrays for equality using Arrays.equals() after sorting
- Finally, print to console
Note : use https://ingesanagram.appspot.com/ for generating difference sequence of Anagram strings
AnagramsProgram.java
package in.bench.resources.anagrams;
import java.util.Arrays;
public class AnagramsProgram {
public static void main(String[] args) {
// invoke checkAnagrams
checkAnagrams("Silent", "Listen");
checkAnagrams("School Master", "The Classroom");
checkAnagrams("School Master", "The Classroom");
checkAnagrams("Fiber", "Brief");
checkAnagrams("Peek", "Keep");
}
public static void checkAnagrams(String str1, String str2) {
// 1. remove spaces in both strings
String string1 = str1.replaceAll("\\s", "");
String string2 = str2.replaceAll("\\s", "");
// 2. set flag for Anagrams
boolean anagramsFlag = true;
// 3. check length of both strings
if(string1.length() != string2.length()) {
// 3.a if length are not equal, then set flag to false
anagramsFlag = false;
}
else {
// 4. convert both String to char[]
char[] charArray1 = string1.toLowerCase().toCharArray();
char[] charArray2 = string2.toLowerCase().toCharArray();
// 5. sort both char[]
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// 6. check Arrays for equality, after sorting
anagramsFlag = Arrays.equals(charArray1, charArray2);
}
// 7. print to console
if(anagramsFlag) {
System.out.println("Both " + string1 + " and "
+ string2 + " are Anagrams");
}
else {
System.out.println(string1 + " and "
+ string2 + " are NOT Anagrams");
}
}
}
Output:
Both Silent and Listen are Anagrams
Both SchoolMaster and TheClassroom are Anagrams
Both SchoolMaster and TheClassroom are Anagrams
Both Fiber and Brief are Anagrams
Both Peek and Keep are Anagrams
Note : There are various other ways to check whether 2 Strings are Anagrams or not
Happy Coding !!
Happy Learning !!