[英]How do you ignore white spaces and punctuation?
How do you make this return the palindrome boolean value ignoring spaces and punctuation?你如何让这个返回忽略空格和标点符号的回文布尔值?
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");
}
}
Check out String.replaceAll
, you define what you want to replace, in this case, whitespaces and punctuation, so we will use \\\\W
as what we want to find and replace it with nothing.查看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");
}
}
Sample Output样本输出
type in a string to check if its a palindrome or not
r';:.,?!ace car
racecar is a palindrome
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.