Java Reference
In-Depth Information
The
insert
methods take two parameters. The first is the index at which
to insert characters into the
StringBuilder
. The second is the value to
insert, after conversion to a
String
if necessary. Here is a method to put
the current date at the beginning of a buffer:
public static StringBuilder addDate(StringBuilder buf) {
String now = new java.util.Date().toString();
buf.insert(0, now).insert(now.length(), ": ");
return buf;
}
The
addDate
method first creates a string with the current time using
java.util.Date
, whose default constructor creates an object that repres-
ents the time it was created. Then
addDate
inserts the string that repres-
ents the current date, followed by a simple separator string. Finally, it
returns the buffer it was passed so that invoking code can use the same
kind of method concatenation that proved useful in
StringBuilder
's own
methods.
The
reverse
method reverses the order of characters in the
StringBuild-
er
. For example, if the contents of the buffer are
"good"
, the contents
after
reverse
are
"doog"
.
You can remove part of the buffer with
delete
, which takes a starting
and ending index. The segment of the string up to but
not
including the
ending index is removed from the buffer, and the buffer is shortened.
You can remove a single character by using
deleteCharAt
.
You can also replace characters in the buffer:
public StringBuilder
replace(int start, int end, String str)
Replace the characters starting at
start
up to but
not
includ-
ing
end
with the contents of
str
. The buffer is grown or shrunk
as the length of
str
is greater than or less than the range of
characters replaced.