简体   繁体   English

Java,检查String是否是回文。不区分大小写

[英]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. 我想编写一个java方法,如果字符串是回文,则返回true。

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. 我的问题在于它没有考虑这样的词: Race car是一个回文。

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. 测试这是否是回文的最佳方法是什么,不区分大小写并忽略标点符号。

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. 如果需要,请使用以下正则表达式,以便在Palindrome中保留偶数numeric字符。 Else, you can just remove the 0-9 from the regex. 否则,你可以从正则表达式中删除0-9

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. 这是一个非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 (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 使用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 : 有关更多信息,请参阅StringStringBuilder的文档:

You can also find it by googling " Java 7 String " and clicking the first result. 您也可以通过Google搜索“ Java 7 String ”并单击第一个结果来找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM