问题
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.
回答1:
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());
回答2:
Try this ..
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);
}
回答3:
Use the below regex, to keep even numeric
characters in the Palindrome, if needed. Else, you can just remove the 0-9
from the regex.
String palindrome = "..." // from elsewhere
String regex = "[^A-Za-z0-9]";
boolean isPalindrome = palindrome.equals(new StringBuilder(palindrome.replaceAll(regex, "").toLowerCase()).reverse().toString());
回答4:
Here is a non regex
solution.
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 (A-Z 65-90) and (a-z 97-122)
{
newStr = newStr + c[i];
}
}
boolean isPalindrome = newStr.toLowerCase().equals(new StringBuilder(newStr.toLowerCase()).reverse().toString());
System.out.println(isPalindrome);
}
}
回答5:
convert to lower case
use a regex to remove everything but letters
reverse the string using a StringBuilder
compare the 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("[^a-z]", "");
String reverse = new StringBuilder(forward).reverse().toString();
return forward.equals(reverse);
}
For more info, see the documentation for String and StringBuilder:
- String.toLowerCase()
- String.replaceAll()
- StringBuilder.reverse()
You can also find it by googling "Java 7 String" and clicking the first result.
来源:https://stackoverflow.com/questions/15401630/java-check-if-a-string-is-a-palindrome-case-insensitive