Java Reference
In-Depth Information
StringBuffer phrase = new StringBuffer("one two three four");
String substring = "two";
String replacement = "twenty";
// Find start of last occurrence of "two"
int position = phrase.lastIndexOf(substring);
phrase.replace(position, position+substring.length(), replacement);
The first three statements define the original StringBuffer object, the substring to be replaced, and
the string to replace the substring . The next statement uses the lastIndexOf() method to find the position
of the first character of the last occurrence of substring in phrase . The last statement uses the replace()
method to substitute replacement in place of substring . To get the index value for one beyond the last
character of substring , you just add the length of substring to its position index. Because replacement
is a string containing more characters than substring , the length of the string in phrase is increased, and
the new contents are "one twenty three four" .
I have not bothered to insert code to check for the possibility of −1 being returned in the preceding code
fragment, but naturally in a real-world context it is essential to do this to avoid the program being terminated
when the substring is not present.
Inserting Strings
To insert a string into a StringBuffer object, you use the insert() method of the object. The first argu-
ment specifies the index of the position in the object where the first character is to be inserted. For example,
if buf contains the string "Many hands make light work" , the statement
buf.insert(4, " old");
inserts the string " old" starting at index position 4, so buf contains the string "Many old hands make
light work" after executing this statement.
Many versions of the insert() method accept a second argument of any of the same range of types that
apply to the append() method, so you can use any of the following with the insert() method:
In each case the string equivalent of the second argument is inserted starting at the index position speci-
fied by the first argument.
If you need to insert a subset of an array of type char[] into a StringBuffer object, you can call the
version of insert() that accepts four arguments, shown below:
insert(int index, char[] str, int offset, int length)
This method inserts a substring into the StringBuffer object starting at position index . The substring is
the String representation of length characters from the str[] array, starting at position offset .
If the value of index is outside the range of the string in the StringBuffer object, or the offset
or length values result in illegal indexes for the array str , then an exception of type StringIn-
dexOutOfBounds Exception is thrown.
Search WWH ::

Custom Search