Summary: In this programming example, we will learn multiple ways to check anagram strings in Java.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Wikipedia

Example:

Method 1: Using substring()

The idea is to one by one pick a character from string-I and remove the same from string-II.

At the end of the process, if the length of the string-II successfully reduces to 0 then the given two strings are anagram, otherwise not.

To remove the characters from string-II, we use the apply substring() method on string-II.

Output:

Anagram

Note: If any character of string-I doesn’t appear in string-II, then they are not anagrams.

Method 2: Using StringBuffer class

In this method, we use the same logic as the above program but instead of the substring() method, we use the StringBuffer class to remove characters from the second string.

Output:

Not an Anagram

Method 3: Using Char Array

In this method, we transform strings into char arrays and check their similarity using the Arrays.equals() method after sorting them in ascending order using the Arrays.sort() method.

If both the arrays turn out to be equal then they are Anagram, otherwise not.

Here is the implementation of the idea in Java:

Output:

Anagram

These were the three ways using which we can check whether the two strings are Anagram of each other or not.

Leave a Reply

three × 4 =