Java Program to check whether two strings are Anagram of each other

Two strings are called anagrams if they contain same set of character but in different order. In this post, we will learn how to check whether the two strings are anagram or not.


Implementation Using Java:

import java.util.Arrays;
public class CheckAnagram {
	public static void isAnagram(String s1, String s2)
	{
		String str1= s1.replaceAll("//s", " ");
		String str2=s2.replaceAll("//s", " ");
		boolean status= true;
		if(str1.length()!=str2.length())
		{
			status=false;
		}
		else
		{
			char[] array1=str1.toLowerCase().toCharArray();
			char[] array2=str2.toLowerCase().toCharArray();
			Arrays.sort(array1);
			Arrays.sort(array2);
			status= Arrays.equals(array1,array2);
		}
		if(status)
		{
			System.out.println("The Strings are anagram");
		}
		else
		{
			System.out.println("The Strings are not anagram");
		}
	}
          public static void main(String[] args) {
		isAnagram("keEp","pEek");
		isAnagram("SilenT Cat","Listen Cat");
	}
}
Input:"keEp", "pEek"
Output:The Strings are anagram.
Input: "SilenT cat", "Listen Cat"
Output: The Strings are anagram.

Happy Coding!

Follow us on Instagram @programmersdoor

Join us on Telegram @programmersdoor


Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem.

Follow Programmers Door for more.

#blog #interview #placement #learn #computer #science

        Contact Us

programmersdoor@gmail.com

  • LinkedIn
  • Facebook
  • Instagram

©2023 by Programmers Door