Java Program to Check if The Given Strings Are Anagram or Not

In this post we’ll see a Java program to check if the given strings are anagram or not. Two strings are called anagrams if you can get the second string by rearranging all of the  letters in the other string.

As example – Keep and Peek, Dormitory and Dirty room, Listen and Silent

Java program to check if the given strings are anagram or not can be written using the following logic-

  1. By sorting the strings– If you sort both the strings after removing any spaces. Then both the strings should be equal.
  2. By iterating– You can iterate one of the string and search for each character in another string, if each character is found once in the second string then the strings are anagram.

Java program to check for anagrams using sort logic

import java.util.Arrays;

public class AnagramStrings {
  public static void main(String[] args) {
    checkIfAnagram("Dormitory", "Dirty room");
    checkIfAnagram("fried", "fired");
    checkIfAnagram("friend", "fried");
  }
	
  private static void checkIfAnagram(String str1, String str2){
    boolean flag;
    // replace all spaces
    String firstString = str1.toLowerCase().replaceAll("\\s", "");
    String secondString = str2.toLowerCase().replaceAll("\\s", "");

    if(firstString.length() != secondString.length()){
       flag = false;
    }else{
      // sort and compare strings
      firstString = sort(firstString);
      secondString = sort(secondString);
      flag = firstString.equals(secondString);
    }
    if(flag){
      System.out.println(str1 + " and " + str2 + " are anagrams");
    }else{
      System.out.println(str1 + " and " + str2 + " are not anagrams");
    }
  }
	
  // Method for sorting the string
  private static String sort(String str) {
    char[] charArray = str.toCharArray();
    Arrays.sort(charArray);
    return new String(charArray);
  }
}

Output

Dormitory and Dirty room are anagrams
fried and fired are anagrams
friend and fried are not anagrams

Java program to check for anagrams using iteration logic

You can use iteration logic to check if the given strings are anagrams or not. For that you need to iterate one of the string char by char and search for the same char in the second string. Each character of the first string should be there in the second string.
Ensure that, if found, character is also deleted from the second string. Not doing that will result in matching the same character again if first string has any character occurring more than once.

public class AnagramStrings {
  public static void main(String[] args) {
    checkIfAnagram("The eyes", "they see");
    checkIfAnagram("peek", "keep");
    checkIfAnagram("friend", "fried");
  }
	
  private static void checkIfAnagram(String str1, String str2){
    boolean flag = true;
    int index;
    // replace all spaces
    String firstString = str1.toLowerCase().replaceAll("\\s", "");
    String secondString = str2.toLowerCase().replaceAll("\\s", "");
    // length check
    if(firstString.length() != secondString.length()){
      System.out.println(str1 + " and " + str2 + " are not anagrams");
      return;
    }

    char[] strArray = firstString.toCharArray();
    StringBuilder sb = new StringBuilder(secondString);
    for(char c : strArray){
      // search for char in second String
      index = sb.indexOf(""+c);
      // If char is found delete it from the second string
      // so that there is no false match for the similar char
      if(index != -1){
        sb.deleteCharAt(index);
      }else{ 
        flag = false;
        break;
      }  
    }
    if(flag){
      System.out.println(str1 + " and " + str2 + " are anagrams");
    }else{
      System.out.println(str1 + " and " + str2 + " are not anagrams");
    }
  }
}

Output

The eyes and they see are anagrams
peek and keep are anagrams
friend and fried are not anagrams

Related Posts

That’s all for the topic Java Program to Check if The Given Strings Are Anagram or Not. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.