delete( ) and deleteCharAt( )
You can delete characters within a StringBuffer by using the methods delete( ) and
deleteCharAt( ). These methods are shown here:
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
The delete( ) method deletes a sequence of characters from the invoking object. Here,
startIndex specifies the index of the first character to remove, and endIndex specifies an index
one past the last character to remove. Thus, the substring deleted runs from startIndex to
endIndex­. The resulting StringBuffer object is returned.
1
The deleteCharAt( ) method deletes the character at the index specified by loc. It returns
the resulting StringBuffer object.
Here is a program that demonstrates the delete( ) and deleteCharAt( ) methods:
// Demonstrate delete() and deleteCharAt()
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
The following output is produced:
After delete: This a test.
After deleteCharAt: his a test.
replace( )
You can replace one set of characters with another set inside a StringBuffer object by calling
replace( ). Its signature is shown here:
StringBuffer replace(int startIndex, int endIndex, String str)
The substring being replaced is specified by the indexes startIndex and endIndex. Thus, the
substring at startIndex through endIndex1 is replaced. The replacement string is passed in str.
­
The resulting StringBuffer object is returned.
The following program demonstrates replace( ):
// Demonstrate replace()
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home