1import java.util.Arrays;
2
3public class AnagramString {
4 static void isAnagram(String str1, String str2) {
5 String s1 = str1.replaceAll("\\s", "");
6 String s2 = str2.replaceAll("\\s", "");
7 boolean status = true;
8 if (s1.length() != s2.length()) {
9 status = false;
10 } else {
11 char[] ArrayS1 = s1.toLowerCase().toCharArray();
12 char[] ArrayS2 = s2.toLowerCase().toCharArray();
13 Arrays.sort(ArrayS1);
14 Arrays.sort(ArrayS2);
15 status = Arrays.equals(ArrayS1, ArrayS2);
16 }
17 if (status) {
18 System.out.println(s1 + " and " + s2 + " are anagrams");
19 } else {
20 System.out.println(s1 + " and " + s2 + " are not anagrams");
21 }
22 }
23
24 public static void main(String[] args) {
25 isAnagram("Keep", "Peek");
26 isAnagram("Mother In Law", "Hitler Woman");
27 }
28}
29/*OUTPUT
30*Keep and Peek are anagrams
31*MotherInLaw and HitlerWoman are anagrams
32*/
1 static boolean isAnagram(String a, String b) {
2
3 String sortedA = "";
4 Object[] aArr = a.toLowerCase().chars().sorted().mapToObj(i -> (char) i).toArray();
5 for (Object o: aArr) {
6 sortedA = sortedA.concat(o.toString());
7 }
8
9
10 String sortedB = "";
11 Object[] bArr = b.toLowerCase().chars().sorted().mapToObj(i -> (char) i).toArray();
12 for (Object o: bArr) {
13 sortedB = sortedB.concat(o.toString());
14 }
15
16 if(sortedA.equals(sortedB))
17 return true;
18 else
19 return false;
20 }