top of page

Java Program to check whether two strings are Anagram or Not?



What is Anagram?

Two strings are said to be anagrams if they make a meaningful word by rearranging or shuffling the letters of the string. In other words, we can say that two strings are anagrams if they contain the same characters but in different order.


Anagram means re-arranging the letter. For example:

  1. RESTFUL => FLUSTER

  2. FORTY FIVE => OVER FIFTY

  3. RACE => CARE

  4. CHEATER => TEACHER

  5. EVIL => VILE

  6. ELEVEN PLUS TWO => TWELVE PLUS ONE


Algorithm:

STEP 1: Initialize two strings: str 1 and str 2

STEP 2: Find the length of the string

STEP 3: Compare the length of the string

a. if the length is not equal then the string is not an anagram.

b. if the length is equal:

a. convert the sting into character

b. sort both the arrays using sort()

c. compare the string using equal()

c. Pass the variable in the if statement.

if the statement is true, then the string is an anagram otherwise not an anagram


Code:

import java.util.Arrays;
import java.util.Scanner;

class Main {
  public static void main(String[] args) {

    // create an object of Scanner class
    Scanner input = new Scanner(System.in);

    // take input from users
    System.out.print("Enter first String: ");
    String str1 = input.nextLine();
    System.out.print("Enter second String: ");
    String str2 = input.nextLine();

    // check if length is same
    if(str1.length() == str2.length()) {

      // convert strings to char array
      char[] charArray1 = str1.toCharArray();
      char[] charArray2 = str2.toCharArray();

      // sort the char array
      Arrays.sort(charArray1);
      Arrays.sort(charArray2);

      // if sorted char arrays are same
      // then the string is anagram
      boolean result = Arrays.equals(charArray1, charArray2);

      if(result) {
        System.out.println(str1 + " and " + str2 + " are anagram.");
      }
      else {
        System.out.println(str1 + " and " + str2 + " are not anagram.");
      }
    }
    else {
      System.out.println(str1 + " and " + str2 + " are not anagram.");
    }

    input.close();
  }
}

Output:



Sofia Sondh

The Tech Platform

0 comments

Recent Posts

See All

Comments


bottom of page