Menu
Topics Index
...
`


Strings > StringBuffer >
Siva Nookala - 20 Feb 2017
The substring of StringBuffer is used to obtain the substring from the StringBuffer. It is similar to substring method in Strings.

There are two forms of substring. The first form is :
String substring(int startIndex, int endIndex);

This will extract a substring of a StringBuffer from startIndex till the endIndex but won't include the character at endIndex.

The otherform of substring is:
String substring(int startIndex);

This form will extract substring from startIndex till the end of the buffer.

Here is the example program on both forms of substring.
SubstringExample String Buffer
class PrintSubstring
{
    public static void main(String arg[])
    {
        StringBuffer name = new StringBuffer("Soundarya");
        String firstPart = name.substring(0, 5);
        String secondPart = name.substring(5);
        System.out.println(firstPart);
        System.out.println(secondPart);
        // String thirdPart = name.substring(0, 10); // Won't work // LINE A    
    }
}
OUTPUT

Sound
arya

DESCRIPTION

This program shows the two forms of substring of StringBuffer class. The first output line is using the first form of substring i.e substring(int startindex, int endindex). So the output will be Sound i.e starting from 0 position of name to position 5 of name ("Soundarya") but not including position 5
The second output line is using the second form of substring i.e using substring(int startindex). The output will be arya which implies string starting at position 5 of name to end of string name.

THINGS TO TRY
  • Print substrings using various indices like (0, 8), (0, 9)
  • Uncomment LINE A - to see the StringIndexOutOfBoundsException, Since the endIndex 10 is greater than the length of name

Dependent Topics : Java Character Extraction - toCharArray() Method In Java  Java equals method vs == Operator  Java regionMatches() Method - String Comparison  Java String trim() Method - trim() Method In Java  Java charAt() And setCharAt() Methods in StringBuffer  Java append() Method In StringBuffer  Java setLength() Method In StringBuffer Class 

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App