delete() StringBuffer Example

delete() StringBuffer Example

Deleting a group of characters with delete() StringBuffer

To manipulate string, java.lang.StringBuffer class comes with many methods, otherwise which will take long laborious coding as in C/C++. One such method is delete(int, int) that deletes a group of characters.

What Java API says of delete() StringBuffer:
  • public synchronized java.lang.StringBuffer delete(int startIndex, int endIndex): Deletes a group of characters from buffer starting from startIndex to endIndex-1. Throws StringIndexOutOfBoundsException if the argument index numbers are more than the buffer size.
Following delete() StringBuffer example illustrates the method.


delete() StringBuffer
Output screenshot on delete() StringBuffer Example

sb1.delete(2, 5);

Deletes the characters with index numbers 2, 3 and 4. That is, 3 characters are deleted. We have seen earlier how to delete a single character in StringBuffer.

sb1.delete(100, 200);

Throws StringIndexOutOfBoundsException as 100 and 200 index numbers does not exist in StringBuffer object sb1.

Leave a Reply

Your email address will not be published. Required fields are marked *