Java Reference
In-Depth Information
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
34
35
StringBuilder stringBuilder =
new
StringBuilder();
// Examine each char in the string to skip alphanumeric char
s.length()
36
for
(
int
i =
0
; i <
; i++) {
37
if
(
Character.isLetterOrDigit(s.charAt(i))
) {
stringBuilder.append(s.charAt(i));
38
39 }
40 }
41
42
add letter or digit
// Return a new filtered string
43
return
stringBuilder.toString();
44 }
45
46
/** Create a new string by reversing a specified string */
47
public static
String reverse(String s) {
48 StringBuilder stringBuilder =
new
StringBuilder(s);
49
stringBuilder.reverse();
// Invoke reverse in StringBuilder
50
return
stringBuilder.toString();
51 }
52 }
Enter a string:
Ignoring nonalphanumeric characters,
is ab<c>cb?a a palindrome? true
ab<c>cb?a
Enter a string:
Ignoring nonalphanumeric characters,
is abcc><?cab a palindrome? false
abcc><?cab
The
filter(String s)
method (lines 31-44) examines each character in string
s
and
copies it to a string builder if the character is a letter or a numeric character. The
filter
method returns the string in the builder. The
reverse(String s)
method (lines 47-51) cre-
ates a new string that reverses the specified string
s
. The
filter
and
reverse
methods both
return a new string. The original string is not changed.
The program in Listing 9.1 checks whether a string is a palindrome by comparing pairs of
characters from both ends of the string. Listing 9.4 uses the
reverse
method in the
StringBuilder
class to reverse the string, then compares whether the two strings are equal
to determine whether the original string is a palindrome.
9.15
✓
✓
What is the difference between
StringBuilder
and
StringBuffer
?
Check
9.16
How do you create a string builder from a string? How do you return a string from a
string builder?
Point
9.17
Write three statements to reverse a string
s
using the
reverse
method in the
StringBuilder
class.
9.18
Write three statements to delete a substring from a string
s
of
20
characters, starting
at index
4
and ending with index
10
. Use the
delete
method in the
StringBuilder
class.
9.19
What is the internal storage for characters in a string and a string builder?