Java Reference
In-Depth Information
40 }
41
42
// 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: ab<c>cb?a
Ignoring nonalphanumeric characters,
is ab<c>cb?a a palindrome? true
Enter a string: abcc><?cab
Ignoring nonalphanumeric characters,
is abcc><?cab a palindrome? false
The
filter(String s)
method (lines 31-44) examines each character in string
s
and cop-
ies 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) creates 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 5.14 checks whether a string is a palindrome by comparing pairs
of characters from both ends of the string. Listing 10.10 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.
10.26
What is the difference between
StringBuilder
and
StringBuffer
?
10.27
How do you create a string builder from a string? How do you return a string from a
string builder?
10.28
Write three statements to reverse a string
s
using the
reverse
method in the
StringBuilder
class.
10.29
Write three statements to delete a substring from a string
s
of
20
characters, start-
ing at index
4
and ending with index
10
. Use the
delete
method in the
String-
Builder
class.
10.30
What is the internal storage for characters in a string and a string builder?
10.31
Suppose that
s1
and
s2
are given as follows:
✓
✓
Check
Point
StringBuilder s1 =
new
StringBuilder(
"Java"
);
StringBuilder s2 =
new
StringBuilder(
"HTML"
);
Show the value of
s1
after each of the following statements. Assume that the state-
ments are independent.
a.
s1.append(
" is fun"
);
b.
s1.append(s2);
Search WWH ::
Custom Search