After you set your variable “original
” to the next line of text, you can call the replaceAll()
string method to strip away any unwanted characters with a specifier parameter. Also, you can call toLowerCase()
to get all lower case strings.
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to check if it is a palindrome");
original = in.nextLine();
original = original.replaceAll("[^a-zA-Z]","").toLowerCase();
replaceAll()
uses a regular expression to search for the specified text and replaces it with the second parameter value.
Here’s a quick example for the palindrome “racecar”:
String original = "rA89293cEC@Ar";
original = original.replaceAll("[^a-zA-Z]","").toLowerCase();
System.out.println(original);
1
solved how to make my program check if its a palindrome by ignoring non-alpha characters and white spaces [closed]