Java Reference
In-Depth Information
This appends the string
" exactly"
to
buf
, so after executing this statement
buf
contains
"The number
is 9912.34 exactly"
.
You may be somewhat bemused by the plethora of
append()
method options, so let's collect all the pos-
sibilities together. You can append any of the following types to a
StringBuffer
object:
In each case the
String
equivalent of the argument is appended to the string in the
StringBuffer
object.
I haven't discussed type
Object
yet — I included it in the table here for the sake of completeness. You
learn about this type of object in Chapter 6.
Finding the Position of a Substring
You can search the buffer of a
StringBuffer
object for a given substring by calling the
indexOf()
method
or the
lastIndexOf()
method. The simpler of the two versions of this method requires just one argument,
which is the string you are looking for, and the method returns the index position of the last occurrence of
the string you are searching for as a value of type
int
. The method returns −1 if the substring is not found.
For example:
StringBuffer phrase = new StringBuffer("one two three four");
int position = phrase.lastIndexOf("three");
The value returned is the index position of the first character of the last occurrence of
"three"
in
phrase
,
which is 8. Remember, the first character is at index position 0. Of course, if the argument to the
lastIn-
dexOf()
method was
"t"
, the result would be the same because the method finds the last occurrence of the
substring in the buffer.
The second version of the
lastIndexOf()
method requires an additional argument that specifies the in-
dex position in the buffer where the search is to start. For example:
position = phrase.lastIndexOf("three", 8);
This statement searches backward through the string for the first character of the substring starting at in-
dex position 8 in
phrase
, so the last nine characters (index values 9 to 17) in the buffer are not examined.
Even through
"three"
extends beyond index position 8, it will be found by this statement and 8 will be
returned. The index constraint is on the search for the first character, not the whole string.
Replacing a Substring in the Buffer
You use the
replace()
method for a
StringBuffer
object to replace a contiguous sequence of characters
with a given string. The string that you specify as the replacement can contain more characters than the sub-
string being replaced, in which case the string is extended as necessary. The
replace()
method requires
three arguments. The first two are of type
int
and specify the start index in the buffer and one beyond the
end index of the substring to be replaced. The third argument is of type
String
and is the string to be inser-
ted. Here's an example of how you might use the
replace()
method: