I’m writing a program to check whether a pair of Strings (entered by the user) are anagrams or not. I’ve already did with the standard way to sort both of the strings using Arrays.sort()
but I also thought of an alternative version not requiring any sorting and ended up with this:
import java.util.Scanner; public class Anagrams { public static void main(String[] args) { String s1, s2; try (Scanner sc = new Scanner(System.in)) { System.out.println("Enter the two words: "); s1 = sc.nextLine().toLowerCase().replace(" ", ""); s2 = sc.nextLine().toLowerCase().replace(" ", ""); } if (s1.length() == s2.length() && isAnagram(s1, s2)) { System.out.format("%s is an anagram of %s.", s1, s2); } else { System.out.format("'%s' and '%s' are not anagrams.", s1, s2); } } public static boolean isAnagram(String s1, String s2) { return (sumOfChars(s1) == sumOfChars(s2)); } public static int sumOfChars(String s) { int sum = 0; for (char c : s.toCharArray()) { sum += c; } return sum; } }
I know this isn’t perfect but it does work with most of the anagram pairs that exist in the dictionary (that I’ve tested). Can I improve anything here or should I forgo this?