Thursday 5 November 2015

Write a program to check if two strings are anagrams or not.


An anagram is a type of word play, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once. Any word or phrase that exactly reproduces the letters in another order is an anagram.

For example:-    William Shakespeare = I am a weakish speller
                         Debit card = Bad credit
                         Dormitory = Dirty Room         
                         School master = The classroom
  

Sample Program:-

 import java.util.Arrays;  
 /**  
  * @author Dixit  
  *  
  */  
 public class AnagramStrings {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           String first="Dormitory";  
           String second="Dirty Room";  
           // sort both the string  
           String sortedFirstString=sortString(first.toLowerCase().toCharArray());  
           String sortedSecondString=sortString(second.toLowerCase().toCharArray());  
           if(sortedFirstString.trim().equals(sortedSecondString.trim()))  
           {  
                System.out.println("Anagrams");  
           }  
           else  
           {  
                System.out.println("Not Anagrams");  
           }  
      }  
      private static String sortString(char[] cs) {  
           Arrays.sort(cs);  
           return new String(cs);  
      }  
 }  

Output:-

 Anagrams  


Enjoy Programming.

No comments:

Post a Comment