numbers – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Sun, 06 Dec 2020 09:12:27 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg numbers – Programmerbay https://programmerbay.com 32 32 Java program to check if two strings are Anagram or not https://programmerbay.com/java-program-to-check-if-two-strings-are-an-anagram-or-not/ https://programmerbay.com/java-program-to-check-if-two-strings-are-an-anagram-or-not/#respond Tue, 07 Jul 2020 08:49:12 +0000 https://www.programmerbay.com/?p=4167 The Java program checks if two given strings are anagram or not. It can be done in two ways, first is by comparing each character of a string, and the second way is by sort the given strings and then compare it.

What is an Anagram String?

When two strings are having exactly the same number of characters where each and every character in both strings are identical without considering the order.

For example, rail and liar are two anagrams, as both have the same number of characters, only the fact is that the letters are rearranged to form meaningful words.

Java program to check if two Strings are Anagram or not by Comparing each character

Program:

/**
Check if two Strings are anagrams by Comparing each character
**/

public class StringAnagram {

public static void main(String[] args) {
String first = "Programmerbay";
String second= "bayprogrammer";
char[] ch1 = first.toLowerCase().toCharArray();
char[] ch2 = second.toLowerCase().toCharArray();
int i,j,count1,count2;
int firstLen = ch1.length;
int secondLen = ch2.length;

if(firstLen==secondLen)
{
count1=0;
count2=0; 
for(i=0;i<firstLen;i++)
{
count1++;
for(j=0;j<firstLen;j++)
{
if(ch1[i]==ch2[j]) 
{
count2++;
break;
}

}
}
}else{
count1=0;
count2=1;
}
if(count1==count2)
System.out.println(first+" and "+second+ " are Anagrams");
else
System.out.println(first+" and "+second+ " are't Anagrams");
}

}

Output:

Programmerbay and bayprogrammer are Anagrams

Java program to check if two Strings are Anagram or not by using the Sort method

Program:

/**
Check if two Strings are anagrams by using the Sort method
**/

import java.util.Arrays;

public class StringAnagram {

    public static void main(String[] args) {
        String first = "Programmerbay";
        String second = "bayprogrammer";
        char[] firstArr = first.toLowerCase().toCharArray();
        char[] secondArr = second.toLowerCase().toCharArray();
        Arrays.sort(firstArr);
        Arrays.sort(secondArr);
        if (String.valueOf(firstArr).equals(String.valueOf(secondArr))) {
            System.out.println("They are anagrams!");
        } else {
            System.out.println("They are not anagrams!");

        }

    }

}

Output: 

They are anagrams!

]]>
https://programmerbay.com/java-program-to-check-if-two-strings-are-an-anagram-or-not/feed/ 0