gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:12:59 25 4
gpt4 key购买 nike

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。在程序中,我应该忽略空格和标点符号,并制作回文,例如“A man, a plan, a canal, Panama”。我想我已经解决了空白问题,但不知道如何忽略所有标点符号。

最佳答案

你可以使用 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();.

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com