-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnagramChecker.java
More file actions
43 lines (35 loc) · 1.42 KB
/
AnagramChecker.java
File metadata and controls
43 lines (35 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.Arrays;
import java.util.Scanner;
public class AnagramChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter two strings
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter the second string: ");
String str2 = scanner.nextLine();
// Check if the strings are anagrams
if (areAnagrams(str1, str2)) {
System.out.println("The strings \"" + str1 + "\" and \"" + str2 + "\" are anagrams.");
} else {
System.out.println("The strings \"" + str1 + "\" and \"" + str2 + "\" are not anagrams.");
}
scanner.close();
}
public static boolean areAnagrams(String str1, String str2) {
// Remove spaces and convert to lowercase
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
// Check if lengths are the same
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);
// Check if sorted char arrays are equal
return Arrays.equals(charArray1, charArray2);
}
}