substring() StringBuffer Example

substring() StringBuffer Example


java.lang.StringBuffer class comes with many methods to manipulate string. One of the methods is overloaded substring() method used to extract part of the characters present in the buffer.

What Java API says about substring() StringBuffer:
  • public synchronized java.lang.String substring(int index1): Returns a string with the characteres of StringBuffer starting from index number index1 to the end. Throws StringIndexOutOfBoundsException if the argument is more than buffer size or less than 0.
  • public synchronized java.lang.String substring(int startIndex, int endIndex): Returns a string with the characters of StringBuffer starting from index number startIndex and ending with endIndex-1. Throws StringIndexOutOfBoundsException if the argument is more than buffer size or less than 0 or endIndex < startIndex.

Following substring() StringBuffer example illustrates the usage of this overloaded method in all possible ways.


substring() StringBuffer
Output screen on substring() StringBuffer first Example

Here delimiter is ' .'

str1 = sb2.substring(firstDot+1, lastDot);

Plus 1 for firstDot is to avoid the first dot in the output. lastDot goes anyhow one back.

Another example to swap letters. To swap the buffer contents and return as a buffer. To print CDAB for ABCD.


ima1
Output screenhot on substring() StringBuffer second Example

Leave a Reply

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