Java Reference
In-Depth Information
There's another version of
insert()
that you can use to insert a substring of a
String
or
StringBuffer
object into a
StringBuffer
object. The first argument is the offset index for the insertion; the second is the
reference to the source of the substring; the third argument is the index for the first character of the sub-
string; and the last argument is the index of one beyond the last character in the substring.
NOTE
If you look in the JDK documentation for
StringBuffer
, you see parameters for
insert()
and other methods of type
CharSequence
. This type allows a
String
or
StringBuffer
reference to be supplied (as well as some other types). I avoid discussing
CharSequence
further at this point because it is different from a class type and it needs an
in-depth explanation. I explain this in Chapter 6.
Extracting Characters from a Mutable String
The
StringBuffer
class includes the
charAt()
and
getChars()
methods, both of which work in the same
way as the methods of the same name in the
String
class which you've already seen. The
charAt()
method
extracts the character at a given index position, and the
getChars()
method extracts a range of characters
and stores them in an array of type
char[]
starting at a specified index position.
You should note that there is no equivalent to the
getBytes()
method for
StringBuffer
objects.
However you can obtain a
String
object from a
CharBuffer
object by calling its
toString()
method,
then you can call
getBytes()
for the
String
object to obtain the
byte[]
array corresponding to the
StringBuffer
object.
Other Mutable String Operations
You can change a single character in a
StringBuffer
object by using the
setCharAt()
method. The first
argument indicates the index position of the character to be changed, and the second argument specifies the
replacement character. For example, the statement
buf.setCharAt(3, 'Z');
sets the fourth character in the string to
'Z'
.
You use the
deleteCharAt()
method to remove a single character from a
StringBuffer
object at the
index position specified by the argument. For example:
StringBuffer phrase = new StringBuffer("When the boats come in");
phrase.deleteCharAt(10);
After these statements have executed,
phrase
contains the string
"When the bats come in"
.
If you want to remove several characters from a
StringBuffer
object you use the
delete()
method.
This method requires two arguments: The first is the index of the first character to be deleted, and the second
is the index position following the last character to be deleted. For example:
phrase.delete(5, 9);