不考虑空格、标点符号和大小写的回文程序
我正在尝试创建一个回文程序,在确定字符串是否为回文时不考虑空格、标点符号以及大小写。
我如何更改此代码以执行我之前所说的操作?
package palindrome;
import java.util.Scanner;
public class Palindrome {
public static void main (String[] args)
{
String str, another = "y";
int left, right;
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 (str.charAt(left) == str.charAt(right) && left < right)
{
left++;
right--;
}
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();
}
} }
I am trying to create a Palindrome program that doesn't consider spaces, punctuation, and uppercase and lowercase when determining whether a string is a palindrome.
How can I change this code given to do what I stated earlier?
package palindrome;
import java.util.Scanner;
public class Palindrome {
public static void main (String[] args)
{
String str, another = "y";
int left, right;
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 (str.charAt(left) == str.charAt(right) && left < right)
{
left++;
right--;
}
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();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您当前的代码查看变量
str
并检查从左到右和从右到左读取的字符是否相同(也就是说,毕竟,回文是什么)。目前,它对用户输入的原始字符串执行此操作。要更改此设置,请在内部
while
循环之前对变量str
进行一些过滤。我将让您弄清楚到底要过滤什么/如何过滤,但请查看 String 类,如indexOf()
、replace()
和substring()
。Your current code looks at the variable
str
and checks if characters are the same reading left-to-right and right-to-left (that is, after all, what a palindrome is).It currently does that on the original string that the user typed in. To change this, before your inner
while
-loop, do some filtering on your variablestr
. I'll leave it to you to figure out exactly what/how to filter, but have a look at some useful methods in the String class, likeindexOf()
,replace()
andsubstring()
.