Java Reference
In-Depth Information
13.4.1. Modifying the Buffer
There are several ways to modify the buffer of a StringBuilder object,
including appending to the end and inserting in the middle. The simplest
method is setCharAt , which changes the character at a specific position.
The following replace method does what String.replace does, except that
it uses a StringBuilder object. The replace method doesn't need to create
a new object to hold the results, so successive replace calls can operate
on one buffer:
public static void
replace(StringBuilder str, char oldChar, char newChar) {
for (int i = 0; i < str.length(); i++)
if (str.charAt(i) == oldChar)
str.setCharAt(i, newChar);
}
The setLength method truncates or extends the string in the buffer. If
you invoke setLength with a length smaller than the length of the cur-
rent string, the string is truncated to the specified length. If the length
is longer than the current string, the string is extended with null char-
acters ( '\\u0000' ).
There are also append and insert methods to convert any data type to
a String and then append the result to the end or insert the result at
a specified position. The insert methods shift characters over to make
room for inserted characters as needed. The following types are conver-
ted by these append and insert methods:
Object
String
CharSequence
char[]
boolean
char
int
long
 
 
Search WWH ::




Custom Search