Thursday 9 May 2013

How to check if two strings are ANAGRAM's or not?

An Anagram is the rearrangement of the letters of a word into another word. 
For Ex: LISTEN and SILENT are Anagrams



SOLUTION 1;


sort both the Strings and compare them. if equal then they are said to be anagrams otherwise not.

sample code snippet in java:

.......
.......

String inputString1 = "SILENT";
String inputString2 = "LISTEN";

boolean checkWhetherAnagramorNot(String inputString1,String inputString2)

{


        char[] chars = inputString1.toCharArray();
        Arrays.sort(chars);
        String sorted1 = new String(chars);
        //System.out.println(sorted1);
        chars = inputString2.toCharArray();
        Arrays.sort(chars);
        String sorted2 = new String(chars);
        //System.out.println(sorted2);
      
         if(sorted1.equals(sorted2))
               return true;
         else
              return false;


}
.........

.........


SOLUTION 2: