Java Reference
In-Depth Information
java.lang.StringBuilder
+append(data: char[]): StringBuilder
+append(data: char[], offset: int, len: int):
StringBuilder
+append(v:
aPrimitiveType
): StringBuilder
Appends a
char
array into this string builder.
Appends a subarray in
data
into this string builder.
Appends a primitive type value as a string to this
builder.
Appends a string to this string builder.
Deletes characters from
startIndex
to
endIndex-1
.
+append(s: String): StringBuilder
+delete(startIndex: int, endIndex: int):
StringBuilder
+deleteCharAt(index: int): StringBuilder
+insert(index: int, data: char[], offset: int,
len: int): StringBuilder
+insert(offset: int, data: char[]):
StringBuilder
+insert(offset: int, b:
aPrimitiveType
):
StringBuilder
+insert(offset: int, s: String): StringBuilder
+replace(startIndex: int, endIndex: int, s:
String): StringBuilder
+reverse(): StringBuilder
+setCharAt(index: int, ch: char): void
Deletes a character at the specified index.
Inserts a subarray of the data in the array into the builder
at the specified index.
Inserts data into this builder at the position offset.
Inserts a value converted to a string into this builder.
Inserts a string into this builder at the position offset.
Replaces the characters in this builder from
startIndex
to
endIndex-1
with the specified string.
Reverses the characters in the builder.
Sets a new character at the specified index in this
builder.
F
IGURE
9.12
The
StringBuilder
class contains the methods for modifying string builders.
The
StringBuilder
class also contains overloaded methods to insert
boolean
,
char
,
char array
,
double
,
float
,
int
,
long
, and
String
into a string builder. Consider the
following code:
insert
stringBuilder.insert(
11
,
"HTML and "
);
Suppose
stringBuilder
contains
Welcome to Java
before the
insert
method is
applied. This code inserts
"HTML and "
at position 11 in
stringBuilder
( just before the
J
). The new
stringBuilder
is
Welcome to HTML and Java
.
You can also delete characters from a string in the builder using the two
delete
methods,
reverse the string using the
reverse
method, replace characters using the
replace
method,
or set a new character in a string using the
setCharAt
method.
For example, suppose
stringBuilder
contains
Welcome to Java
before each of the
following methods is applied:
stringBuilder.delete(8, 11)
changes the builder to
Welcome Java
.
stringBuilder.deleteCharAt(8)
changes the builder to
Welcome o Java.
stringBuilder.reverse()
changes the builder to
avaJ ot emocleW
.
stringBuilder.replace(11, 15, "HTML")
changes the builder to
Welcome to HTML
.
stringBuilder.setCharAt(0, 'w')
sets the builder to
welcome to Java
.
delete
deleteCharAt
reverse
replace
setCharAt
All these modification methods except
setCharAt
do two things:
Change the contents of the string builder
■
Return the reference of the string builder
■
ignore return value
For example, the following statement
StringBuilder stringBuilder1 = stringBuilder.reverse();