如何使其返回palindrome布尔值,忽略空格和标点符号?
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");
}
}
答案 0 :(得分:1)
签出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