Sunday, July 15, 2018

Given Strings are anagrams or not using java



What is String Anagram?

"An anagram is a type of word, the result of rearranging the letters of a word or phrase to produce a new word or phrase, using all the original letters exactly once.

for Example: 'java' can be rearranged as - 'vaaj' or 'vjaa' -all characters are equal in both the words. So this is called string anagram.

Now we will see how to write a java program to check whether given strings are anagram or not.


package com.siva;

import java.util.Arrays;

public class StringAnagramTest {
 
 
  public boolean isStringAnagram(String s1, String s2){
   char[] charArray1 = s1.toCharArray();
   char[] charArray2 = s2.toCharArray();
   Arrays.sort(charArray1);
   Arrays.sort(charArray2);
   boolean stringAnagram = Arrays.equals(charArray1, charArray2);
   return stringAnagram;
  }
  
  public static void main(String[] args) {
   StringAnagramTest test = new StringAnagramTest();
    String str1 ="test";
    String str2 ="sett";
  boolean stringAnagram = test.isStringAnagram(str1, str2);
   if(stringAnagram){
    System.out.println("Given Strings["+str1+"] and ["+str2 +"] are anagrams");
   }else{
    System.out.println("Given Strings["+str1+"] and ["+str2 +"] are not anagrams");
   }
}

}




We can provide any value as input for both the strings.

Detailed Explanation:

Step 1: Convert given Strings into character array.

Step 2: Sort the converted character array using Arrays.sort

Step 3: compare both the strings using Arrays.equals

There are different ways to implement the same logic by writing our own sorting and equals methods. this is simple way to find the result.

output:



Given Strings[test] and [sett] are anagrams


AddToAny

Contact Form

Name

Email *

Message *