简体   繁体   English

如何在回文式(Java)中消除空白

[英]How to get rid of white space in palindrome (Java)

public class reverserapp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.println("Please Enter a word");
      String str = scan.nextLine();

      String reverse = "";
      for( int i = str.length() - 1; i >= 0; i--)
          reverse += str.charAt(i);

      if(reverse.equalsIgnoreCase(str))
          System.out.println("Palindrome");
      else System.out.println("Not Palindrome");

    }

}

This is my palindrome code. 这是我的回文代码。 I'm doing this for a small assignment. 我正在做一个小任务。 I can get single words to work but if I write a something like "Don't nod" it shows up as not palindrome. 我可以使用单个单词来工作,但是如果我写类似“ Do n't nod”的字样,则表明它不是回文。 How can I achieve this? 我该如何实现? I'd like for my code to ignore punctuation's and white space. 我想让我的代码忽略标点符号和空格。

So in the end result should be like "dontnod" 所以最终结果应该像“ dontnod”

Thanks in advance for any help, complete noob at this. 预先感谢您的任何帮助,请完成这一步。

Remove all non-letter characters, then put the resulting String to lower case . 删除所有非字母字符,然后将结果String为小写。

str = str.replaceAll("[^a-zA-Z]", "");
str = str.toLowerCase();

You can use the replace function from StringUtils . 您可以使用StringUtils中replace函数。

Example: 例:

StringUtils.replace("asdasd aaaa", " ", ""); //-> output: asdasdaaaa

You can define a regex to remove punctuation and space, and perform a String replace on input, eg: 您可以定义一个regex来删除标点符号和空格,并在输入上执行字符串replace ,例如:

String regex = "[\\p{Punct}\\s]";
String input = "don't nod";
System.out.println(input.replaceAll(regex, ""));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM