1.

In what way should two strings be compared to determine whether they are anagrams?

Answer»

If two strings contain the same characters but in a different ORDER, they can be said to be anagrams. Consider dusty and study. In this case, dusty's characters can be formed into a study, or study's characters can be formed into dusty. Below is a java program to check if two strings are anagrams or not.

import java.util.Arrays;public class CheckAngagram { public static void main(String[] args) { String str1 = "BORED"; String str2 = "Robed"; //Convert strings to lowercase str1 = str1.toLowerCase(); str2 = str2.toLowerCase(); // Check to see if the lengths are the same if(str1.length() == str2.length()) { // convert strings into char array char[] str1charArray = str1.toCharArray(); char[] str2charArray = str2.toCharArray(); // sort the char array Arrays.sort(str1charArray); Arrays.sort(str2charArray); // if the SORTED char arrays are same or IDENTICAL // then the strings are anagram boolean result = Arrays.equals(str1charArray, str2charArray); if(result) { System.out.println(str1 + " and " + str2 + " are anagrams of each other."); } else { System.out.println(str1 + " and " + str2 + " are not anagrams of each other."); } } else { System.out.println(str1 + " and " + str2 + " are not anagrams of each other."); } }}

Output:

bored and robed are anagrams of each other.

In the above program, there are two strings i.e., str1 and str2. Here, we are comparing str1 and str2 to determine if they are anagrams. The strings are first converted to lowercase since Java is case-sensitive and B and b are two different characters in Java. Here,

  • str1.toCharArray(): Convert or transform the string into a char array.
  • Arrays.sort(): It sorts the char arrays.
  • Arrays.equals(): Checks or verifies if sorted char arrays are EQUAL.

In the case where sorted arrays are equal, the strings are anagrams.



Discussion

No Comment Found