A program to check if two strings are Anagrams and Pallindrome in JAVA
E.g"Dormitory-Dirty Room"-> Anagram ,Not Pallindrome
"Madam-madam" -> Anagram, Pallindrome
" School Master- The Classroom"-> Anagram, Not Pallindrome
package com.anagram;
import java.util.Arrays;
import java.util.Scanner;
/**
*
* @author anuz
*/
public class Program {
public static void main(String[] args) {
String firstString, secondString;
boolean isAnagram = false;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a String:");
firstString = scanner.nextLine().toLowerCase().trim();
System.out.print("Enter another number:");
secondString = scanner.nextLine().toLowerCase().trim();
if (checkAnagram(firstString, secondString)) {
System.out.println("Anagram");
//to check if two strings are pallindrome
StringBuilder sb = new StringBuilder(secondString);
if (firstString.equalsIgnoreCase(sb.reverse().toString())) {
System.out.println("Pallindrome");
}else{
System.out.println("Not Pallindrome");
}
} else {
System.out.println("Not Anagram");
}
}
private static boolean checkAnagram(String firstString, String secondString) {
//filter string-> remove whitespace and special characters
//replace all characters except a-z alphabets and digits with an empty string
firstString = firstString.replaceAll("[^a-zA-Z0-9]", "").trim();
secondString = secondString.replaceAll("[^a-zA-Z0-9]", "").trim();
if (firstString.length() == secondString.length()) {
char[] charArrayOfFirstString = firstString.toCharArray();
char[] charArrayOfSecondString = secondString.toCharArray();
//check if both sorted arrayofchar are equal
Arrays.sort(charArrayOfFirstString);
Arrays.sort(charArrayOfSecondString);
return Arrays.equals(charArrayOfFirstString, charArrayOfSecondString);
} else {
return false;
}
}
}
OUTPUT:
-----------------------------------------------------------------------
No comments:
Post a Comment