Anagram: Program to check if two strings are anagram


A string is said to be an anagram of another string if they satisfy the following conditions

  • They consist of same letters in their composition
  • The count of each letter is equal in both String

 

General Idea

  • Based on the condition we can find if two strings are an anagram of each other
  • We remove any spaces in the string so the resulting string is just set of characters
  • Then we sort the String
  • Similary we process the other string
  • Compare the two strings, if they are same then the original string is an anagram of other string

 

Java Code
import java.util.*;

class Anagram{
    
      public char[] trimAndSort(String value){
        String copy = value.replaceAll("\\s","").toLowerCase();
        char[] stringChar = copy.toLowerCase().toCharArray();
        Arrays.sort(stringChar);
        return stringChar;
      }
    
      public boolean checkAnagram(String a, String b){
        return Arrays.equals(trimAndSort(a),trimAndSort(b));
      }
    
      public static void main(String args[]){
        Anagram aa  = new Anagram();
        boolean isAnagram =	aa.checkAnagram(" Fermonte", "montefer");
        System.out.print("Strings Fermonte & montefer ? ");
        System.out.println(isAnagram == true ? "Its an anagram" : "Its not anagram");
    
        boolean isThisAnagram =	aa.checkAnagram("A decimal point", "I m a dot in place");
        System.out.print("Strings 'A decimal point' & 'I m a dot in place' ? ");
        System.out.println(isThisAnagram == true ? "Its an anagram" : "Its not anagram");
      }
 }   
Output

Strings Fermonte & montefer ? Its an anagram
Strings 'A decimal point' & 'I m a dot in place' ? Its an anagram



Thanks for feedback.