Java, Check if String is a palindrome. Case insensitive

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

Here is what I still have:

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

My problem is that he does not consider a word like: Race car palindrome.

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

What is the best way to check if it is a palindrome, with case insensitive and ignoring punctuation.

+4
source share
5 answers

Use this regex to remove all punctuation and spaces and convert them to lowercase

 String palindrome = "..." // from elsewhere boolean isPalindrome = palindrome.replaceAll("[^A-Za-z]", "").toLowerCase().equals(new StringBuilder(palindrome.replaceAll("[^A-Za-z]", "").toLowerCase()).reverse().toString()); 
+7
source

Try it.

 public static void main(String[] args) { boolean notPalindrome = false; String string = "Doc, note, I dissent. A fast never prevents a fatness. I diet on cod"; string = string.replaceAll("[^a-zA-Z]+","").toLowerCase(); char[] array = string.toCharArray(); for(int i=0, j=array.length-1; i<j; i++, j--) { if(array[i] != array[j]) { notPalindrome = true; break; } } System.out.println(string + " is palindrome? " + !notPalindrome); } 
+1
source

Use the regex below to keep even numeric characters in the palidron, if necessary. Alternatively, you can simply remove 0-9 from the regular expression.

 String palindrome = "..." // from elsewhere String regex = "[^A-Za-z0-9]"; boolean isPalindrome = palindrome.equals(new StringBuilder(palindrome.replaceAll(regex, "").toLowerCase()).reverse().toString()); 
0
source

Here is a solution not regex .

 public class so4 { public static void main(String args[]) { String str = "Doc, note, I dissent. A fast never prevents a fatness. I diet on cod"; char c[] =str.toCharArray(); String newStr=""; for(int i=0;i<c.length;i++) { if( (c[i]>=65 && c[i]<=90) || (c[i]>=97 && c[i]<=122)) //check ASCII values (AZ 65-90) and (az 97-122) { newStr = newStr + c[i]; } } boolean isPalindrome = newStr.toLowerCase().equals(new StringBuilder(newStr.toLowerCase()).reverse().toString()); System.out.println(isPalindrome); } } 
0
source
  • convert to lowercase

  • use regex to remove everything except letters

  • undo a string using StringBuilder

  • compare strings for equality

code:

 /** * Returns true if s is a palindrome, ignoring whitespace * punctuation, and capitalization. Returns false otherwise. */ public boolean isPalindrome(String s) { String forward = s.toLowerCase().replaceAll("[^az]", ""); String reverse = new StringBuilder(forward).reverse().toString(); return forward.equals(reverse); } 

For more information, see the documentation for String and StringBuilder :

You can also find it with googling "Java 7 String" and click the first result.

0
source

Source: https://habr.com/ru/post/1469140/


All Articles