Friday, 6 January 2017

TO CHECK WHETHER TWO STRINGS ARE ANAGRAM IN JAVA

Tags

1. when total number of alphabets in both strings are same.

2. when all the alphabets of 1st string are present in 2nd string , here alphabets are same but their sequence can varry.

For Example :

"base " & "seba " are  anagram as no. of alphabets are 4 in both strings & alphabets are also same.

 
PROGRAM EXAMPLE IN JAVA :


import java.util.*;

public class der {
public static boolean IsAnagram(String arg1,String arg2){
char a[] = arg1.toCharArray();
char b[] = arg2.toCharArray();
int index[] = new int[a.length];
int c=0;
while(c<index.length){
index[c] =0;
c++;
}
int i = 0;
while(i<arg1.length()){
int j=0 , check =0;
while(j<arg2.length()){
if(a[i]==b[j]&&index[j]==0){
index[j]=1;
check=1;
break;
}j++;
}
if(check==0){
return false;
}
i++;
}
return true;
}

public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.println("enter two strings");
String a=inp.next();
String b = inp.next();
 
boolean o =IsAnagram(a,b);
if(o){
System.out.println(a+" is anagram  with "+b);
}
else{
System.out.println("not an anagram");
}
}

}


OUTPUT :

enter two strings
base
seba
base is anagram  with seba









Enter Your Comments Below Emoticon