Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, Check if a String is a palindrome. Case insensitive

I want to write a java method to return true if a string is a palindrome.

Here is what I have so far:

String palindrome = "...";
boolean isPalindrome = palindrome.equals(
   new StringBuilder(palindrome).reverse().toString());

My problem with this is that it does not consider a word like: Race car to be a palindrome.

Doc, note, I dissent. A fast never prevents a fatness. I diet on cod.

What is the best way to test if this is a palindrome, with case insensitivity and ignoring punctuation.

like image 670
user2121604 Avatar asked Feb 17 '23 04:02

user2121604


1 Answers

Use this regex to remove all punctuation and spaces and convert it to lower case

String palindrome = "..." // from elsewhere
boolean isPalindrome = palindrome.replaceAll("[^A-Za-z]", "").toLowerCase().equals(new StringBuilder(palindrome.replaceAll("[^A-Za-z]", "").toLowerCase()).reverse().toString());
like image 98
Fr_nkenstien Avatar answered Feb 23 '23 04:02

Fr_nkenstien