This is the first solution to check whether the given two strings are Anagram are not. This program uses toCharArray() method of String Class.
import java.util.Arrays;
import java.util.Scanner;
public class CheckAnagram {
public static void main(String [] args) {
Scanner inpStr=new Scanner(System.in);
System.out.println("Enter an input first line of strings");
String str=inpStr.nextLine();
//Converting the input sentence to sequence of characters array in the same order
char[] str1Chars=str.toCharArray();
//Sorting the characters array including with spaces if any available
Arrays.sort(str1Chars);
System.out.println("Enter an input second line of strings");
str=inpStr.nextLine();
char[] str2Chars=str.toCharArray();
Arrays.sort(str2Chars);
inpStr.close();
//Compare the two sorted character array strings, excluding the spaces after converting into lower case for Anagram check
if (String.valueOf(str1Chars).trim().toLowerCase().contentEquals(String.valueOf(str2Chars).trim().toLowerCase()))
System.out.println("Both Line of Strings are Anagram");
else
System.out.println("Both Line of Strings are Not Anagram");
}
}
Enter an input first line of strings
Dormitory Beds
Enter an input second line of strings
dirty rooms bed
Both Line of Strings are Anagram

Leave a comment