回文忽略空格和标点符号

时间:2014-11-09 03:38:43

标签: java

 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;

}

}

我的问题是,例如,如果我做伊娃,我能在洞穴中看到蜜蜂吗?它应该是一个回文,但不能请你帮助我,请尽量不要让它变得复杂。

3 个答案:

答案 0 :(得分:3)

替换:

String b = a.toLowerCase().replaceAll("[^a-z]"," ");

使用

String b = a.toLowerCase().replaceAll("[^a-z]","");

否则,您将用空格替换非字母字符,这会影响对反向字符串的检查。

答案 1 :(得分:0)

您需要删除字符串中的所有非字母:

public class Palindrome {
  public static String strip(String s) {
    return s.toLowerCase().replaceAll("[^a-z]", "");
  }

  public static boolean isPalindrome(String s) {
    for (int i = 0; i < s.length() / 2; i++) {
      if (s.charAt(i) != s.charAt(s.length() - 1 - i)) {
        return false;
      }
    }

    return true;
  }

  public static void main(String[] args) {
    System.out.println(strip("Eva, can I see bees in a cave?"));
    System.out.println(isPalindrome(strip("Eva, can I see bees in a cave?")));
  }
}

输出:

evacaniseebeesinacave
true

答案 2 :(得分:0)

public class PalindromeStringWithReverse {
    public static void main(String[] args) {
        String str = "21raceca r12";
        str = str.replaceAll(" ", "");
        boolean isPalindrome = false;
        for (int i = 0; i < str.length() / 2; i++) {
            if (str.charAt(i) == str.charAt((str.length() - 1) - i)) {
                isPalindrome = true;
                continue;
            }
            isPalindrome = false;
        }
        if (isPalindrome) {
            System.out.println("Palindrome");
        } else {
            System.out.println("not palindrome");
        }

    }
}