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

我要做的是制作一个程序,该程序将单词或短语作为输入并根据它是否为回文返回真或假。在程序中,我应该忽略空格和标点符号,并制作诸如“A man, a plan, a canal, Panama”之类的回文。我想我已经解决了空格问题,但不知道如何忽略所有标点符号。

4

2 回答 2

8

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

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

输出:

letterOnly = Amanaplanacanal巴拿马

如果要减少代码的长度,还可以使用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.");
}

编辑

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

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

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

于 2013-01-17T00:24:13.597 回答
1

Apache Commons Lang中的StringUtils类有一些可能很方便的方法,包括和. 将您的字符串与您要删除的所有标点字符的字符串一起传递将返回一个无标点符号的字符串。deleteWhitespace()difference()difference()

于 2013-01-17T00:37:26.303 回答