Java Reference
In-Depth Information
13.4.2. Getting Data Out
To get a
String
object from a
StringBuilder
object, you simply invoke
the
toString
method. If you need a substring of the buffer, the
substring
methods works analogously to those of
String
. If you want some or all
of the contents as a character array, you can use
getChars
, which is ana-
logous to
String.getChars
.
public void
getChars(int srcBegin, int srcEnd, char[] dst, int dstBe-
gin)
Copies characters from this
StringBuilder
into the specified ar-
ray. The characters of the specified substring are copied in-
to the character array, starting at
dst[dstBegin]
. The specified
substring is the part of the string buffer from
srcBegin
up to
but
not
including
srcEnd
.
Here is a method that uses
getChars
to remove part of a buffer:
public static StringBuilder
remove(StringBuilder buf, int pos, int cnt) {
if (pos < 0 || cnt < 0 || pos + cnt > buf.length())
throw new IndexOutOfBoundsException();
int leftover = buf.length() - (pos + cnt);
if (leftover == 0) { // a simple truncation
buf.setLength(pos);
return buf;
}
char[] chrs = new char[leftover];
buf.getChars(pos + cnt, buf.length(), chrs, 0);
buf.setLength(pos);
buf.append(chrs);
return buf;
}