package Chapter8;import javax.swing.JOptionPane;public class PalindromeIgnoreNonAlphanumeric {/** Main method */public static void main(String[] args) {// Prompt the user to enter a stringString s = JOptionPane.showInputDialog("Enter a string:");// Declare and initialize output stringString output = "Ignoring non-alphanumeric characters, \nis "+ s + " a palindrome? " + isPalindrome(s);// Display the resultJOptionPane.showMessageDialog(null, output);}/** Return true if a string is a palindrome */public static boolean isPalindrome(String s) {// Create a new string by eliminating non-alphanumeric charsString s1 = filter(s);// Create a new string that is the reversal of s1String s2 = reverse(s1);// Compare if the reversal is the same as the original stringreturn s2.equals(s1);}/** Create a new string by eliminating non-alphanumeric chars */public static String filter(String s) {// Create a string bufferStringBuilder strBuf = new StringBuilder();// Examine each char in the string to skip alphanumeric charfor (int i = 0; i < s.length(); i++) {if (Character.isLetterOrDigit(s.charAt(i))) {strBuf.append(s.charAt(i));}}// Return a new filtered stringreturn strBuf.toString();}/** Create a new string by reversing a specified string */public static String reverse(String s) {StringBuilder strBuf = new StringBuilder(s);strBuf.reverse(); // Use the reverse method for StringBuilder objectreturn strBuf.toString();}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。