Java,检查String是否是回文。不区分大小写 [英] Java, Check if a String is a palindrome. Case insensitive

查看:184
本文介绍了Java,检查String是否是回文。不区分大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个java方法来返回true,如果一个字符串是一个回文。

I want to write a java method to return true if a string is a palindrome.

这里是我到目前为止:

String palindrome = "...";
boolean isPalindrome = palindrome.equals(
   new StringBuilder(palindrome).reverse().toString());

我的问题是它不考虑一个词:汽车为回文。

My problem with this is that it does not consider a word like: Race car to be a palindrome.

Doc, note, I dissent. A fast never prevents a fatness. I diet on cod.

测试这是否是回文,不区分大小写和忽略标点符号的最佳方法。 / p>

What is the best way to test if this is a palindrome, with case insensitivity and ignoring punctuation.

推荐答案

使用此正则表达式删除所有标点符号和空格并将其转换为小写

Use this regex to remove all punctuation and spaces and convert it to lower case

String palindrome = "..." // from elsewhere
boolean isPalindrome = palindrome.replaceAll("[^A-Za-z]", "").toLowerCase().equals(new StringBuilder(palindrome.replaceAll("[^A-Za-z]", "").toLowerCase()).reverse().toString());

这篇关于Java,检查String是否是回文。不区分大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆