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 StringBuilderreplace(int start, int end, String str)
Replace the characters starting at start up to but not including 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.
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 analogous to
String.getChars.
public voidgetChars(int srcBegin, int srcEnd, char[] dst, int
dstBegin)
Copies characters from this StringBuilder into the specified array. The
characters of the specified substring are copied into 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;
}
First remove ensures that the array references will stay in bounds. You could handle the actual exception
later, but checking now gives you more control. Then remove calculates how many characters follow the
removed portion. If there are none, it truncates and returns. Otherwise, remove retrieves them using
getChars and then truncates the buffer and appends the leftover characters before returning.