import java.util.Arrays;
public class AnagramChecker {
public static void main(String[] args) {
String str1 = "silent";
String str2 = "listen";
if (areAnagrams(str1, str2)) {
System.out.println(str1 + " and " + str2 + " are anagrams");
} else {
System.out.println(str1 + " and " + str2 + " are not anagrams");
}
}
public static boolean areAnagrams(String str1, String str2) {
// Remove all whitespace from both strings and convert to lowercase
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
// If the two strings are not of the same length, they can't be anagrams
if (str1.length() != str2.length()) {
return false;
}
// Convert each string to a character array, sort the arrays, and compare them
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2);
}
}
In this program, we define a method called areAnagrams that takes two strings as arguments and returns a boolean indicating whether or not they are anagrams of each other. The method first removes all whitespace from both strings and converts them to lowercase. Then it checks if the two strings are of the same length; if they are not, they cannot be anagrams. Finally, it converts each string to a character array, sorts the arrays, and compares them using the
Arrays.equals method. If the sorted arrays are equal, the strings are anagrams; otherwise, they are not.
In the main method, we define two strings (str1 and
str2) and call the areAnagrams method with those strings. If the method returns
true, we print a message indicating that the strings are anagrams; otherwise, we print a message indicating that they are not.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In this program, we define a method called areAnagrams that takes two strings as arguments and returns a boolean indicating whether or not they are anagrams of each other. The method first removes all whitespace from both strings and converts them to lowercase. Then it checks if the two strings are of the same length; if they are not, they cannot be anagrams. Finally, it converts each string to a character array, sorts the arrays, and compares them using the Arrays.equals method. If the sorted arrays are equal, the strings are anagrams; otherwise, they are not.
In the main method, we define two strings (str1 and str2) and call the areAnagrams method with those strings. If the method returns true, we print a message indicating that the strings are anagrams; otherwise, we print a message indicating that they are not.