Home / JAVA / ISC Class 12 / JAVA program to check Anagram of a Words

JAVA program to check Anagram of a Words

Program in Java to Check if the word is a anagram of a given word: An anagram is a type of word play, the result of rearranging the letters of a word to produce a new word or we can say the possible string we make by rearranging the letter of word.

Example:
Anagram of the word ‘ABC’ are : ABC, BAC, BCA, ACB, CAB, CBA

import java.io.*;
 
public class AnagramMatch
{
  public static boolean anagram(String s1, String s2) 
  {
        if (s1.length() != s2.length()) return false;
        int[] alphanum = new int[256];
        int chars = 0;       //no of unique characters
        int num_completed_s2 = 0;
        char[] s1_array = s1.toCharArray();
        for (char c : s1_array) 
        {         // count number of each char in s1.
             if (alphanum[c] == 0) ++chars;
             ++alphanum[c];
        }
        for (int i = 0; i < s2.length(); ++i) 
        {
        int a = (int) s2.charAt(i);
        if (alphanum[c] == 0) 
             {           // if you find more of char c in s1 than in a return false.
              return false;
             }
              --alphanum[c];
              if (alphanum[c] == 0) 
             {
                 ++num_completed_s2;
                 if (num_completed_s2 == chars) 
                 {                                        // it’s a match if s2 has been processed completely
                      return i == s2.length() - 1;
                 }
              }
        }
        return false;
 }
 public static void main (String[] args) {
    System.out.println ("Enter the first string: ");
    String string1 = "";
    String string2 = "";
    InputStreamReader input1 = new InputStreamReader(System.in);
    BufferedReader reader1 = new BufferedReader(input1);
    try
    {
            string1 = reader1.readLine();
    }
    catch(Exception e1){}
    System.out.println ("Enter the second string: ");
    InputStreamReader input2 = new InputStreamReader(System.in);
    BufferedReader reader2 = new BufferedReader(input2);
    try
    {
        string2 = reader2.readLine();
    }
    catch(Exception e2){}
    boolean value = anagram(string1,string2);
    if(value == true)   
    System.out.println("The string are anagrams of each other");
    else
    System.out.println("The string are NOT anagrams of each other");
 }
}

 

Also See:   Java program to swap two numbers without using a third variable

Check Also

Java program to implement polymorphism

Java program to implement polymorphism: Polymorphism is a technique in java with which you can ...

Leave a Reply

Your email address will not be published. Required fields are marked *