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 isPalindro
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:
You can also find it by googling "Java 7 String" and clicking the first result.
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());
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());
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);
}
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);
}
}