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;
}
}
我要做的是制作一个程序,将一个单词或短语作为输入,并根据它是否是回文而返回true或false。在程序中,我应该忽略空格和标点符号,并制作诸如“男人,计划,运河,巴拿马”之类的回文。我想我已经解决了空白问题,但无法弄清楚如何忽略所有标点符号。
答案 0 :(得分:7)
您可以使用a regular expression删除字符串中的所有非字字符:\\W
代表非字字符
String s = "A man, a plan, a canal, Panama.";
String lettersOnly = s.replaceAll("[\\W]", "");
System.out.println("lettersOnly = " + lettersOnly);
输出:
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.");
}
修改强>
如果您需要坚持循环,只需检查字符是字母:
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();
。
答案 1 :(得分:1)
Apache Commons Lang中的StringUtils
类有一些方法可能很方便,包括deleteWhitespace()
和difference()
。将字符串传递给difference()
以及要删除的所有标点符号字符串将返回无标点字符串。