Java Reference
In-Depth Information
sb2
.
append
(
"World"
);
// Get the StringBuilder's value as a String, and print it.
String s2
=
sb2
.
toString
();
System
.
out
.
println
(
s2
);
// Now do the above all over again, but in a more
// concise (and typical "real-world" Java) fashion.
System
.
out
.
println
(
new
new
StringBuilder
()
.
append
(
"Hello"
)
.
append
(
','
)
.
append
(
' '
)
.
append
(
"World"
));
}
}
In fact, all the methods that modify more than one character of a
StringBuilder
's contents
(i.e.,
append()
,
delete()
,
deleteCharAt()
,
insert()
,
replace()
, and
reverse()
) return
a reference to the builder object to facilitate this “fluent API” style of coding.
As another example of using a
StringBuilder
, consider the need to convert a list of items
into a comma-separated list, while avoiding getting an extra comma after the last element of
the list. Code for this is shown in
Example 3-3
.
Example 3-3. StringBuilderCommaList.java
// Method using regexp split
StringBuilder sb1
=
new
new
StringBuilder
();
for
for
(
String word
:
SAMPLE_STRING
.
split
(
" "
)) {
iif
(
sb1
.
length
() >
0
) {
sb1
.
append
(
", "
);
}
sb1
.
append
(
word
);
}
System
.
out
.
println
(
sb1
);
// Method using a StringTokenizer
StringTokenizer st
=
new
new
StringTokenizer
(
SAMPLE_STRING
);
StringBuilder sb2
=
new
new
StringBuilder
();
while
while
(
st
.
hasMoreElements
()) {
sb2
.
append
(
st
.
nextToken
());
iif
(
st
.
hasMoreElements
()) {
sb2
.
append
(
", "
);