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

空扰寡人 提交于 2019-11-28 02:03:37

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());

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);
}

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());

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);
}
}
  1. convert to lower case

  2. use a regex to remove everything but letters

  3. reverse the string using a StringBuilder

  4. 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!