Java Reference
In-Depth Information
10.11.3 Case Study: Ignoring Nonalphanumeric Characters When
Checking Palindromes
Listing 5.14, Palindrome.java, considered all the characters in a string to check whether it
is a palindrome. Write a new program that ignores nonalphanumeric characters in checking
whether a string is a palindrome.
Here are the steps to solve the problem:
1. Filter the string by removing the nonalphanumeric characters. This can be done by
creating an empty string builder, adding each alphanumeric character in the string
to a string builder, and returning the string from the string builder. You can use the
isLetterOrDigit(ch) method in the Character class to check whether character
ch is a letter or a digit.
2. Obtain a new string that is the reversal of the filtered string. Compare the reversed string
with the filtered string using the equals method.
The complete program is shown in Listing 10.10.
L ISTING 10.10
PalindromeIgnoreNonAlphanumeric.java
1 import java.util.Scanner;
2
3 public class PalindromeIgnoreNonAlphanumeric {
4 /** Main method */
5 public static void main(String[] args) {
6 // Create a Scanner
7 Scanner input = new Scanner(System.in);
8
9 // Prompt the user to enter a string
10 System.out.print( "Enter a string: " );
11 String s = input.nextLine();
12
13 // Display result
14 System.out.println( "Ignoring nonalphanumeric characters, \nis "
15 + s + " a palindrome? " + isPalindrome(s));
16 }
17
18 /** Return true if a string is a palindrome */
19 public static boolean isPalindrome(String s) {
20 // Create a new string by eliminating nonalphanumeric chars
21 String s1 = filter(s);
22
23 // Create a new string that is the reversal of s1
24 String s2 = reverse(s1);
25
26
check palindrome
// Check if the reversal is the same as the original string
27
return s2.equals(s1);
28 }
29
30
/** Create a new string by eliminating nonalphanumeric chars */
31
public static String filter(String s) {
32
// Create a string builder
33
StringBuilder stringBuilder = new StringBuilder();
34
35
// Examine each char in the string to skip alphanumeric char
36
for ( int i = 0 ; i < s.length(); i++) {
37
if (Character.isLetterOrDigit(s.charAt(i))) {
38
stringBuilder.append(s.charAt(i));
add letter or digit
39 }
 
 
Search WWH ::




Custom Search