An anagram is word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.as example let take two String first string is HELLO and other one string is OHELL ,if we see it we found that both string length is same and character are also same with different order then we can say that these string are anagram of each other.
Example:
To check it by program following is the steps we need to follow...
- Take the strings from keyboard.
- Now convert these string into character array and store it in the character array.
- Now sort the character array using Arrays.sort(array) method.
- now compare each character by character from both array having same index.
import java.util.Scanner;
import
java.util.Arrays;
class
AnagramDemo {
public static void
main(String[] args) {
System.out.println("Enter first string ");
char[]
ch1 = new Scanner(System.in).nextLine().toCharArray();
Arrays.sort(ch1);
System.out.println("Enter second string ");
char[]
ch2 = new Scanner(System.in).nextLine().toCharArray();
Arrays.sort(ch2);
boolean flag
= false;
if
(ch1.length == ch2.length) {
for
(int i = 0; i < ch1.length; i++) {
if
(ch1[i] == ch2[i])
flag
= true;
else
flag
= false;
}
}
if
(flag == true)
System.out.println("Anagram");
else
System.out.println("Non-Anagram");
}
}
Output
Enter first string
HELLO
Enter second string
OHELL
Anagram
Press any key to continue . . .