public static void main(String[] args)
{
Scanner sentence = new Scanner(System.in);
System.out.println("This program will determine if an inputted phrase is a palindrome.");
System.out.println(" ");
System.out.println("Enter a phrase, word, or sentence:");
String a = sentence.nextLine();
String b = a.toLowerCase().replaceAll("[^a-z]"," "); //as long as the words are spelt the same way, the caps don't matter and it ignores spaces and punctuation
System.out.println();
System.out.println(palindromeChecker(b)); //calls method
}
public static String palindromeChecker(String b)
{
String reverse = new StringBuilder(b).reverse().toString();
String c;
if(b.equals(reverse)) {
c = "The word " +b+ " is a palindrome"; }
else {
c = "The word " +b+ " is not a palindrome"; }
return c;
}
}
我的问题是,例如,如果我做伊娃,我可以看到洞穴里的蜜蜂吗?它应该是一个回文,但它不是,你可以帮我解决这个问题,请尽量不要让它变得复杂。
最佳答案
替换:
String b = a.toLowerCase().replaceAll("[^a-z]"," ");
与
String b = a.toLowerCase().replaceAll("[^a-z]","");
否则,您将用空格替换非字母字符,这可能会影响反向字符串的检查。
关于java - 回文忽略空格和标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26824726/