java - 回文忽略空格和标点符号

标签 java

 public static void main(String[] args) 
{
    Scanner sentence = new Scanner(System.in);
    System.out.println("This program will determine if an inputted phrase is a palindrome.");
    System.out.println(" ");
    System.out.println("Enter a phrase, word, or sentence:");
    String a = sentence.nextLine();
    String b = a.toLowerCase().replaceAll("[^a-z]"," "); //as long as the words are spelt the same way, the caps don't matter and it ignores spaces and punctuation
    System.out.println();
    System.out.println(palindromeChecker(b)); //calls method

}

public static String palindromeChecker(String b) 
{
    String reverse = new StringBuilder(b).reverse().toString();
    String c; 
    if(b.equals(reverse)) { 
        c = "The word " +b+ "  is a palindrome"; }
    else {
        c = "The word " +b+ "  is not a palindrome"; }
    return c;

}

}

我的问题是,例如,如果我做伊娃,我可以看到洞穴里的蜜蜂吗?它应该是一个回文,但它不是,你可以帮我解决这个问题,请尽量不要让它变得复杂。

最佳答案

替换:

String b = a.toLowerCase().replaceAll("[^a-z]"," ");

String b = a.toLowerCase().replaceAll("[^a-z]","");

否则,您将用空格替换非字母字符,这可能会影响反向字符串的检查。

关于java - 回文忽略空格和标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26824726/

相关文章:

java - 使空对象不可变的任何标准模式或策略

java - Spring 应用程序在 8 小时后失去与 MySql 的连接。如何正确配置?

java - 当我的方法递归的唯一条件尚未满足时,为什么它会递归?

java - 如何配置 spring boot 应用程序以在 MySQL 上使用 SSL/TLS?

Java UTF8 编码

java - 在 Java 7 或更低版本中,HOWTO 使用在 map 中找到的键/值来过滤 map 对象列表

java - 如何用正则表达式删除第二个子字符串?

java - java中十进制转十六进制的方法

java - 模拟交通信号(单盒)

java - 为什么当文件大小大于 2 MB 时,Java servlet 会给出 ClientAbortException?