top of page

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

Writer's picture: PREETI CHOUHANPREETI CHOUHAN

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.

20 views0 comments

Recent Posts

See All

留言


bottom of page