» » Java program to check two strings are anagrams



  1. package com.javatutorial;
  2.  import java.util.Arrays;

  3. public class CheckAnagramStrings {
  4.   
  5. private static boolean isAnagram(String str1, String str2) {
  6.  
  7.         if (str1.length() != str2.length()) {
  8.             return false;
  9.         }
  10.         str1 = sortCharacters(str1);
  11.         str2 = sortCharacters(str2);
  12.         return str1.equals(str2);
  13.  }
  14.  
  15. private static String sortCharacters(String str) {
  16.         char[] charArray = str.toLowerCase().toCharArray();
  17.         Arrays.sort(charArray);
  18.         return String.valueOf(charArray);
  19.  }

  20.  public static void main(String[] args) {
  21.    
  22.  String str1 = "bemru";
  23.  String str2 = "mureb";
  24.  
  25.  if (isAnagram(str1, str2)) {
  26.           System.out.println(str2 + " is anagram of " + str1);
  27.   } else {
  28.           System.out.println("Strings are not anagrams.");
  29.   }
  30.  
  31. }

  32. }


Output:

  1. mureb is anagram of bemru
     

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu