Anagram of a string is another string with the same characters but order of the characters can be different. For example, Two strings “Listen” and “Silent” are anagram strings as both contain same characters, just the order of the characters is different. Similarly Strings “Race” and “Care” are also anagrams. In this article, you will learn how to write a java program to check two strings are anagram or not.
Program to determine whether two strings are anagram
Steps:
- Convert the given strings in the lowercase letters using toLowerCase() method, this is to perform case insensitive comparison.
- Compare the lengths (find length using length() method) of the given strings, if lengths are not equal then strings cannot be anagram else proceed to next step.
- Copy the characters of the strings into an array using toCharArray() method.
- Sort the arrays using Arrays.sort(). This is to sort the characters in the array in a particular order as the anagram strings characters are in different order. For example, the arrays of strings “race” and “care” are {‘r’, ‘a’, ‘c’, ‘e’} & {‘c’, ‘a’, ‘r’, ‘e’} receptively. After sorting both the arrays are same : {‘a’, ‘c’, ‘e’, ‘r’}
- Compare the sorted arrays, if the arrays are equal then the strings are anagrams else they are not anagram strings.
import java.util.Arrays; public class JavaExample { public static void main (String [] args) { String str1="Race"; String str2="Care"; //Converting the strings to lower case to //perform case insensitive comparison str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); //Comparing the length of the two strings if the lengths //are not equal then strings cannot be anagrams if (str1.length() != str2.length()) { System.out.println("Given strings are not anagram."); } else { //copying the characters of each strings in two different arrays char[] arrayOfStr1 = str1.toCharArray(); char[] arrayOfStr2 = str2.toCharArray(); //Sorting both the arrays using Arrays.sort() Arrays.sort(arrayOfStr1); Arrays.sort(arrayOfStr2); //Comparing the sorted arrays, if equal anagram else not anagram if(Arrays.equals(arrayOfStr1, arrayOfStr2) == true) { System.out.println("Given Strings are anagram."); } else { System.out.println("Given Strings are not anagram."); } } } }
Output:
Given Strings are anagram.
Leave a Reply