问题描述
我已经编写了程序,直到必须忽略它,在线程中使用标点符号和空格为止,我想知道是否有人可以帮助我进行编码?我一直在尝试的东西似乎没有用.这是我到目前为止的内容:
I have the program made up until the point where it has to ignore and punctuations and spaces in the thread and I was wondering if anyone could help me with the coding for that? What I've been trying out doesn't seem to be working. Here is what I have so far:
import java.util.Scanner;
public class PalindromeTester
{
public static void main (String[] args)
{
String str, another = "y";
int left, right;
char charLeft, charRight;
Scanner scan = new Scanner (System.in);
while (another.equalsIgnoreCase("y")) // allows y or Y
{
System.out.println ("Enter a potential palindrome: ");
str = scan.nextLine();
left = 0;
right = str.length() - 1;
while (left < right)
{
charLeft = str.charAt(left);
charRight = str.charAt(right);
if (charLeft == charRight)
{
left++;
right--;
}
else if (charLeft == ',' || charLeft == '.' ||
charLeft == '-' || charLeft == ':' ||
charLeft == ';' || charLeft == ' ')
left++;
else if (charRight == ',' || charRight == '.' ||
charRight == '-' || charRight == ':' ||
charRight == ';' || charRight == ' ')
right--;
else
break;
}
System.out.println();
if (left < right)
System.out.println ("That string is NOT a palindrome.");
else
System.out.println ("That string IS a palindrome.");
System.out.println();
System.out.print ("Test another palindrome (y/n)? ");
another = scan.nextLine();
}
}
}
推荐答案
只是为了澄清吉姆·加里森(Jim Garrison)所说的,您需要的正则表达式如下:
Just to clarify what Jim Garrison said, the regex you need is the following
String m = "Madam, I'm'',.,.'' Adam";
m = m.toLowerCase().replaceAll("\\W", "");
这将仅保留字母和数字,并删除空格和标点符号,即m变为"madamimadam",您可以对该字符串进行常规回文测验.
This will leave only letters and digits and remove whitespace and punctuation, i.e. m will become "madamimadam" and you can run you regular palindrome test on that string.
您可以了解有关正则表达式的更多信息这里
You can learn more about regular expressions here
这篇关于使用Java的回文测试仪,忽略空格和标点符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!