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;
}
}
我要做的是做一个程序,它需要一个单词或短语作为输入,并返回真或假取决于它是否是一个回文。在程序中,我应该忽略空格和标点符号,并生成诸如"一个人,一个计划,一条运河,巴拿马"之类的回文。我想我已经解决了空白的问题,但不知道如何忽略所有的标点符号。
您可以使用正则表达式从字符串中删除所有非单词字符:\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();
。
Apache Commons Lang中的StringUtils
类有一些可能很方便的方法,包括deleteWhitespace()
和difference()
。将您的字符串与您想要删除的所有标点字符的字符串一起传递给difference()
将返回一个没有标点符号的字符串。