If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To check if two strings are anagrams, you need to verify whether they have the same characters in the same frequency. An anagram is a word or phrase formed by rearranging the letters of another word or phrase, typically using all the original letters exactly once. Here's a Java method to check for anagrams:
javaCopy code
import java.util.Arrays;
public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
// Remove spaces and convert both strings to lowercase
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
// Check if the lengths of the strings are the same
if (str1.length() != str2.length()) {
return false;
}
// Convert the strings to char arrays and sort them
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// Compare the sorted char arrays to determine if they are anagrams
return Arrays.equals(charArray1, charArray2);
}
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.");
}
}
}
In this example, we have a method areAnagrams
that takes two strings str1
and str2
as input and returns true
if they are anagrams, and false
otherwise. The method first removes spaces and converts both strings to lowercase using the replaceAll()
and toLowerCase()
methods.
We then check if the lengths of the strings are the same. If they are not the same, they cannot be anagrams, and we return false
.
Next, we convert the strings to character arrays using toCharArray()
and sort them using Arrays.sort()
. Sorting the arrays ensures that characters with the same frequency will appear in the same order in both arrays if the strings are anagrams.
Finally, we compare the sorted character arrays using Arrays.equals()
to determine if they are anagrams. If the arrays are equal, the strings are anagrams, and we return true
; otherwise, we return false
.
In the main
method, we test the areAnagrams
method with two sample strings. If the strings are anagrams, it will print "The strings are anagrams." Otherwise, it will print “The strings are not anagrams.”
Comments: 0