Answer:
Check the explanation
Step-by-step explanation:
import java.util.Scanner;
public class Anagrams {
public static int count(String s, char ch) {
int c = 0;
for (int i = 0; i < s.length(); ++i) {
if (s.charAt(i) == ch) {
c++;
}
}
return c;
}
public static boolean isAnagram(String s1, String s2) {
char ch;
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
for (int i = 0; i < s1.length(); ++i) {
ch = s1.charAt(i);
if (ch != ' ' && count(s1, ch) != count(s2, ch)) {
return false;
}
}
for (int i = 0; i < s2.length(); ++i) {
ch = s2.charAt(i);
if (ch != ' ' && count(s1, ch) != count(s2, ch)){
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the first string: ");
String s1 = in.nextLine();
System.out.print("Enter the second string: ");
String s2 = in.nextLine();
if (isAnagram(s1, s2)) {
System.out.println(s1 + " and " + s2 + " are anagrams");
} else {
System.out.println(s1 + " and " + s2 + " are NOT anagrams");
}
}
}
Kindly check the output image below.