An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
For example : For word CAT anagram are TAC, CTA, ACT, TCA etc.
We are going to write a clean code for the anagram.
Problem
There are two word CAT and TAC, write a code to check these words are anagram ?
Approach
Our approach would be to sort both the string and compare each other, if return true then the strings are anagrams else not anagram.
Code
import java.util.Arrays;
public class Anagram {
public static void main(String[] args) {
String str1 = "cat";
String str2 = "tac";
char[] str1Arr = str1.toCharArray();
char[] str2Arr = str2.toCharArray();
Arrays.sort(str1Arr);
Arrays.sort(str2Arr);
if(String.valueOf(str1Arr).equals(String.valueOf(str2Arr))) {
System.out.println("Anagram");
} else {
System.out.println("Not Anagram");
}
}
}
Run Program