Java Reference
In-Depth Information
the builder's capacity is the size of the array. If the builder's capacity is exceeded, the
array is replaced by a new array. The new array size is
2 * (the previous array
size + 1)
.
Tip
You can use
new StringBuilder(initialCapacity)
to create a
StringBuilder
with a specified initial capacity. By carefully choosing the initial capacity, you can make
your program more efficient. If the capacity is always larger than the actual length of the
builder, the JVM will never need to reallocate memory for the builder. On the other hand, if
the capacity is too large, you will waste memory space. You can use the
trimToSize()
method to reduce the capacity to the actual size.
initial capacity
trimToSize()
9.6.3 Case Study: Ignoring Nonalphanumeric Characters When
Checking Palindromes
Listing 9.1, CheckPalindrome.java, considered all the characters in a string to check whether
it was a palindrome. Write a new program that ignores nonalphanumeric characters in check-
ing 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 cre-
ating 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 9.4.
L
ISTING
9.4
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
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
public static boolean
isPalindrome(String s) {
check palindrome
// Check if the reversal is the same as the original string