This is the second solution to check whether the given two strings are Anagram are not. This program uses deleteCharAt() method of StringBuilder Class.
import java.util.Scanner;
class CheckAnagramByDeletingChars {
public static void main(String[] args) {
Scanner inpStr=new Scanner(System.in);
System.out.println("Enter first line");
String secondLine=inpStr.nextLine();
//Converting the input line to lower case by excluding spaces and store into firstLine stringBuilder variable
StringBuilder firstLine=new StringBuilder(secondLine.replaceAll("\\s", "").toLowerCase());
System.out.println("Enter second line");
secondLine=inpStr.nextLine();
//Converting the second input line to lower case by excluding spaces
secondLine=secondLine.replaceAll("\\s", "").toLowerCase();
inpStr.close();
Boolean isAnagram=true;
//Check the availability of each character from the firstLine (StringBuilder) in the secondLine, if available delete the same from firstLine
while (firstLine.length()>0) {
if (secondLine.contains(String.valueOf(firstLine.charAt(0)))==true)
firstLine.deleteCharAt(0);
else {
isAnagram=false;
break;
}
}
//If all characters of firstLine available in second line, Anagram always have default value true
if (isAnagram==true)
System.out.println("Both input lines are Anagram");
else
System.out.println("Both input lines are not Anagram");
}
}
Enter first line
Integral
Enter second line
trianglE
Both input lines are Anagram

Leave a comment