Thursday 15 June 2017

Program in java to check if two Strings are Anagram or not

Anagram program in java

Program:

package JavaCoders;
import java.util.Arrays;
public class Anagram
{
void ana(String s1,String s2)
{
String st1=s1.replaceAll("\\s", "");
String st2=s2.replaceAll("\\s", "");
boolean b=true;
if(st1.length()!=st2.length())
{
b=false;
}
else
{
char array1[]=st1.toLowerCase().toCharArray();
char array2[]=st2.toLowerCase().toCharArray();
Arrays.sort(array1);
Arrays.sort(array2);
b=Arrays.equals(array1, array2);
}
if(b)
{
System.out.println("These are the Anagrams");
}
else
{
System.out.println("These are not the Anagrams");
}
}
public static void main(String[] args)
{
Anagram an=new Anagram();
an.ana("JavaCoders", "Codjavaers");
an.ana("balwant","Singh");
an.ana("balwant","bawnalt");
}
}

In this program,first we have to supply the two strings as input. After providing input we have to first remove all the spaces contained in the two strings. Then after removing spaces you have to check if both the strings contains same length, as it is the first rule in the program to check for anagrams. If both the strings contains equal length that we proceed further otherwise we are with the result that the strings are not anagrams. Suppose in case we are having same length of strings, then we have to convert both the strings into lowercase using toLowerCase() function and must be stored in array of char type. When these two arrays contains all the values that are in lowercase, then we have to apply the function called sort. sort function will sort these two arrays. After sorting we have to use equals function that will compare these arrays. One thing to remember is that you must have to import package called java.util.Arrays, because this package contains all the functions. One's comparing is done using equals method, the result is saved in b variable of boolean type. If the condition is true, it will print "These are the Anagrams" otherwise "These are not the Anagrams".

OUTPUT:


Program-in-java-to-check-if-two-Strings-are-Anagram-or-not

You can also check this program:

No comments:

Post a Comment

Oracle / PLSQL: FOR LOOP

set serveroutput on; declare a1 varchar2(100); begin select count(*) into a1 from employees; for i in 1..a1 loop dbms_output.put_line...