你如何忽略空格和标点符号?

How do you ignore white spaces and punctuation?

如何使这个 return 忽略空格和标点符号的回文布尔值?

import java.util.Scanner;
public class StringUtil
{
    public static boolean Palindrome(String s)
    {
        if(s.length() == 0 || s.length() == 1)
            return true;

        if(s.charAt(0) == s.charAt(s.length()-1))
            return Palindrome(s.substring(1, s.length()-1));

        return false;
    }

    public static void main(String[]args)
    {
        Scanner check = new Scanner(System.in);
        System.out.println("type in a string to check if its a palindrome or not");
        String p = check.nextLine();
        if(Palindrome(p))
            System.out.println(p + " is a palindrome");
        else
            System.out.println(p+ " is not a palindrome");
    }
}

查看 String.replaceAll,您定义要替换的内容,在本例中为空格和标点符号,因此我们将使用 \W 作为我们要查找的内容并替换为空。

import java.util.Scanner;
public class StringUtil{

public static boolean Palindrome(String s)
{

    if(s.length() == 0 || s.length() == 1)
        return true;

    if(s.charAt(0) == s.charAt(s.length()-1))
        return Palindrome(s.substring(1, s.length()-1));

    return false;

}

public static void main(String[]args)
{
    Scanner check = new Scanner(System.in);
    System.out.println("type in a string to check if its a palindrome or not");
    String p = check.nextLine();

    //We replace all of the whitespace and punctuation 
    p = p.replaceAll("\W", "");

    if(Palindrome(p))
        System.out.println(p + " is a palindrome");
    else
        System.out.println(p+ " is not a palindrome");
}

}

示例输出

type in a string to check if its a palindrome or not
r';:.,?!ace    car
racecar is a palindrome