Java-Get Substring

Get Substring

A substring is a part of another string. For example, the strings “123” and “45” are substrings of the string “12345”. The subString( ) method of the StringBuffer class enables us to extract the substrings from a string. A substring( ) method of the form substring( int startIndex, int endIndex-1 ) will return a substring of length ( endIndex – startIndex ), starting from the position ‘startIndex’ in the given string.

For example, in the following program, the first substring( ) method will return a substring of length ‘3’, starting from the position ‘0’ in the string “C++JAVAPHP”. Thus, this method will return the substring “C++”. Similarly, the second substring( ) method will return the substring “JAVA”. We shall specify only one argument in the substring( ) method, as in the case of str.substring( 7 ). Here, the substring of all but the first ‘7’ characters in the string ‘str’ will be returned. Thus, the substring “PHP” will returned.

Program

sdsdsd


Program Source

public class Javaapp {
    
    public static void main(String[] args) {
        
        StringBuffer str = new StringBuffer(3);
        str.append("C++JAVAPHP");
        
        System.out.println(str.substring(0, 3));
        System.out.println(str.substring(3, 7));
        System.out.println(str.substring(7));
    }
}

Leave a Comment