如何忽略java中的标点符号和空格?

use*_*357 3 java palindrome punctuation

import java.util.Scanner;
public class Ex3 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Please input a word: ");
        String Line = keyboard.nextLine();
        boolean x = isReverse(Line);
        System.out.print("It is " + x + " that this word is a palindrome.");
    }
    public static boolean isReverse(String Line) {
        int length = Line.length();
        boolean x = true;
        String s = "";
        for (int i = 0; i < length; i++) {
            if (Line.charAt(i) != ' ') {
                s += Line.charAt(i);
            }
        }
        for (int i = 0; i < length; i++) {
            if (Line.charAt(i) != Line.charAt(length - 1 -i)) {
                x = false;
            }
        }
        return x;   
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是制作一个程序,它接受一个单词或短语作为输入,并返回true或false,具体取决于它是否是回文.在程序中,我应该忽略空格和标点符号,并制作诸如"男人,计划,运河,巴拿马"之类的回文.我想我已经解决了空白问题,但无法弄清楚如何忽略所有标点符号.

ass*_*ias 7

您可以使用正则表达式从字符串中删除所有非单词字符:\\W表示非单词字符

String s = "A man, a plan, a canal, Panama.";
String lettersOnly = s.replaceAll("[\\W]", "");
System.out.println("lettersOnly = " + lettersOnly);
Run Code Online (Sandbox Code Playgroud)

输出:

lettersOnly = AmanaplanacanalPanama

如果要减少代码的长度,还可以使用StringBuilder#reverse反转字符串:

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please input a word: ");
    String line = keyboard.nextLine();

    String cleanLine = line.replaceAll("[\\W]", "");
    String reverse = new StringBuilder(cleanLine).reverse().toString();
    boolean isPalindrome = cleanLine.equals(reverse);

    System.out.print("It is " + isPalindrome + " that this word is a palindrome.");
}
Run Code Online (Sandbox Code Playgroud)

编辑

如果你需要坚持循环,你可以简单地检查你的循环中字符是字母:

public static boolean isReverse(String Line) {
    int length = Line.length();
    boolean x = true;
    String s = "";
    for (int i = 0; i < length; i++) {
        if ((Line.charAt(i) >= 'a' && Line.charAt(i) <= 'z')
          || (Line.charAt(i) >= 'A' && Line.charAt(i) <= 'Z')) {
            s += Line.charAt(i);
        }
    }
Run Code Online (Sandbox Code Playgroud)

注意:您将遇到问题(A!= a) - 一个简单的解决方法是先将所有字符放在小写字母中String lowerCase = Line.toLowerCase();.