Array-promo

Question

check whether two words  or two sentences are anagrams or not

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class AnagramOrNot
{  
    public static char[] sort(char[] characters)
    {
        int i=0,k=0;
        char ch=' ';
        char[] sorted=new char[characters.length];

        for(ch='a';ch<='z';ch++)
        {
            for(i=0;i< characters.length;i++)
            {
                if(characters[i]==ch)
                {
                    sorted[k]=characters[i];
                    k++;
                }

            }
        }
        return sorted;
    }    

    public static void isAnagram(char[] str1,char[] str2)
    {
        int i=0;
        boolean flag=true;
        for(i=0;i< str1.length;i++)
        {
            if(str1[i]!=str2[i])
            {
                flag=false;
                break;
            }
        }
        if(flag==true)
        {
            System.out.println("Both the words or sentences are  anagram ");   
        }
        else
        {
            System.out.println("Both the words or sentences are not anagram words"); 
        }

    }

    public static void main (String [] args)
    {   
        String wd="",wd1="";
        Scanner sc = new Scanner(System.in);    

        System.out.println("first word or sentence");   
        wd = sc.nextLine();
        System.out.println("second word or sentence");   
        wd1 = sc.nextLine();

        System.out.println("first word or sentence:"+wd);
        System.out.println("Second word or sentence:"+wd1);
        /*Converting both the string to lower case and removing all spaces in them if any*/  

        wd = wd.toLowerCase();  
        wd1 = wd1.toLowerCase();  
        wd=wd.replaceAll(" ", "");
        wd1=wd1.replaceAll(" ", "");

        /*Checking for the length of strings*/  
        if (wd.length() != wd1.length()) 
        {  
            System.out.println("Both the words or sentences are not anagram words");  
        }  
        else 
        {  
            /*Converting both the arrays to character array */ 
            char[] str1 = wd.toCharArray();  
            char[] str2 = wd1.toCharArray();  

            /*Sorting the arrays using sort() method defined above*/
            str1=sort(str1);
            str2=sort(str2);

            isAnagram(str1,str2);
        }  
    }  
}  

				
			

Coding Store

Leave a Reply

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