Java program to Check whether the string is Anagram or not

Wikipedia Definition of Analgram
An anagram is direct word switch or 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;
for example, the word anagram can be rearranged into “nag a ram”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
 
package com.spy.javaforlearn;
 
import java.util.Arrays;
 
public class Analgram 
{
 
	 public void analgramchecking(String s1,String s2)
 
	 {
         //Removing white space
		 String b1=s1.replaceAll("\\s","");
		 String  b2=s2.replaceAll("\\s","");
 
		 //converting string into char array
		char[]  array1=b1.toLowerCase().toCharArray();
 
	    char[]  array2=b2.toLowerCase().toCharArray();
 
 
	    //Sorting array
	    Arrays.sort(array1);		 
	    Arrays.sort(array2);		
 
	    //comparing arrays
	    Boolean b=Arrays.equals(array1,array2);
 
 
	    System.out.println(b1+" and "+b2);
 
	    if(b)
 
	    {
 
	    	System.out.println("String is analgram ");
	    }
 
	    else
	    {
 
	    	System.out.println("String is not analgram");
	    }
 
 
 
 
 
	 }
 
  public static void main(String[] args)
  {
 
	  Analgram a1=new Analgram();
	  a1.analgramchecking("bhavesh", "shvebha");
	  a1.analgramchecking("abc","bac");
	  a1.analgramchecking("xyx","xyz");
 
  }
 
}

output:

1
2
3
4
5
6
7
8
9
 
bhavesh and shvebha
String is analgram 
 
abc and bac
String is analgram 
 
xyx and xyz
String is not analgram

Leave a Reply

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