A simple program to check anagrams in java

programming

This is a simple program in Java. This program can be used to check if the two given strings are anagram. Two given strings are said to be anagrams when they have equal length and same characters are present in both the Strings. An example of anagram strings is SILENT and LISTEN!

Screenshot

Code
import java.util.*;

public class Anagram {
  public static boolean isAnagram(String s1, String s2) {
    if (s1.length() != s2.length()) {
      return false;
    }
    s1 = sortCharacters(s1);

    s2 = sortCharacters(s2);
    return s1.equals(s2);

  }
  public static String sortCharacters(String str) {
    char[] c = str.toLowerCase().toCharArray();
    Arrays.sort(c);
    return String.valueOf(c);
  }
  public static void main(String arg[]) {
    String s1, s2;
    Scanner sc = new Scanner(System.in);
    System.out.println("enter 2 strings");
    s1 = sc.nextLine();
    s2 = sc.nextLine();
    if (isAnagram(s1, s2))
      System.out.println(s1 + "is an anagram" + s2);
    else
      System.out.println(s1 + "is not an anagram" + s2);
  }
}

 

Got anything to say, please do comment here.

Catch me

Sidharth Patnaik

Blogger at Codermag
Tinkerer/Coder/Blogger
Catch me

Latest posts by Sidharth Patnaik (see all)

Related posts