Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}


Here is the output:


After replace: This was a test.

substring( )


You can obtain a portion of aStringBufferby callingsubstring( ). It has the following two
forms:


String substring(intstartIndex)
String substring(intstartIndex, intendIndex)

The first form returns the substring that starts atstartIndexand runs to the end of the
invokingStringBufferobject. The second form returns the substring that starts atstartIndex
and runs throughendIndex–1. These methods work just like those defined for Stringthat
were described earlier.


Additional StringBuffer Methods


In addition to those methods just described,StringBufferincludes several others. They are
summarized in the following table. Notice that several were added by J2SE 5.


Method Description
StringBuffer appendCodePoint(intch) Appends a Unicode code point to the end of the invoking object.
A reference to the object is returned. Added by J2SE 5.
int codePointAt(inti) Returns the Unicode code point at the location specified byi.
Added by J2SE 5.
int codePointBefore(inti) Returns the Unicode code point at the location that precedes
that specified byi.Added by J2SE 5.
int codePointCount(intstar t, intend) Returns the number of code points in the por tion of the invoking
Stringthat are betweenstar tandend–1. Added by J2SE 5.
int indexOf(Stringstr) Searches the invokingStringBufferfor the first occurrence ofstr.
Returns the index of the match, or –1 if no match is found.
int indexOf(Stringstr, intstar tIndex) Searches the invokingStringBufferfor the first occurrence ofstr,
beginning atstar tIndex.Returns the index of the match, or –1
if no match is found.
int lastIndexOf(Stringstr) Searches the invokingStringBufferfor the last occurrence ofstr.
Returns the index of the match, or –1 if no match is found.
int lastIndexOf(Stringstr, intstar tIndex) Searches the invokingStringBufferfor the last occurrence ofstr,
beginning atstar tIndex.Returns the index of the match, or –1
if no match is found.

Chapter 15: String Handling 381

Free download pdf