How To Check If Two Strings Are Anagrams In Java
Chapter:
Miscellaneous
Last Updated:
22-08-2023 17:28:26 UTC
Program:
/* ............... START ............... */
import java.util.Arrays;
public class AnagramChecker {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}
public static boolean areAnagrams(String str1, String str2) {
// Remove spaces and convert to lowercase for case-insensitive comparison
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
// If lengths are different, they can't be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Convert strings to char arrays and sort them
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// Compare sorted char arrays
return Arrays.equals(charArray1, charArray2);
}
}
/* ............... END ............... */
Output
Input :
String str1 = "listen";
String str2 = "silent";
Output:
The strings are anagrams.
Input :
String str1 = "hello";
String str2 = "world";
Output :
The strings are not anagrams.
Notes:
-
This code first removes spaces and converts the strings to lowercase for a case-insensitive comparison. Then, it checks whether the lengths of the strings are the same. If they're not, the strings can't be anagrams. If the lengths are the same, it converts both strings to character arrays, sorts them, and then compares the sorted arrays using Arrays.equals().
- Keep in mind that this approach is relatively simple and works well for small to moderate-sized strings. For extremely large strings or performance-critical scenarios, more optimized algorithms might be needed.