Way2Java

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:

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

public class Demo
{
  public static void main(String args[])
  {						
   StringBuffer sb1 = new StringBuffer("ABCDEFGHI");
   System.out.println("Original string buffer contents: " + sb1);
			                    // using substring(int)
   String str1 = sb1.substring(5);          // returns from 5th character
   System.out.println("sb1.substring(5): " + str1);			
   				            // using substring(int, int)
   str1 = sb1.substring(3, 7);              // returns 3, 4, 5 and 6th character
   System.out.println("sb1.substring(3, 7): " + str1);	
					    //  to extract mail server name
   StringBuffer sb2 = new StringBuffer("www.yahoo.com");
   int firstDot = sb2.indexOf(".");
   int lastDot = sb2.lastIndexOf(".");
   str1 = sb2.substring(firstDot+1, lastDot);
   System.out.println("Your server name: " + str1);
 }
}



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.

public class Demo
{
  public static void main(String args[])
  {						
   StringBuffer sb1 = new StringBuffer("ABCD");
   System.out.println("buffer contents before swapping: " + sb1);
			                             
   String str1 = sb1.substring(0, 2);      // extract first two characters
   String str2 = sb1.substring(2);         // extract last two characters
   
   sb1 = new StringBuffer(str2+str1);
   System.out.println("buffer contents after swapping: " + sb1);
 }
}



Output screenhot on substring() StringBuffer second Example