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 String 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 ‘2’, starting from the position ‘0’ in the string “12042015”. Thus, this method will return the substring “12”. Similarly, the second substring( ) method will return the substring “04”. We shall specify only one argument in the substring( ) method, as in the case of calender.substring( 4 ). Here, the substring of all but the first ‘4’ characters in the string calendar will be returned. Thus, the substring “2015” will returned.

Program

final2

Program Source

public class Javaapp {
    
    public static void main(String[] args){
        
        String calendar = new String("12042015");
        System.out.println("Date  : "+calendar.substring(0, 2));
        System.out.println("Month : "+calendar.substring(2, 4));
        System.out.println("Year  : "+calendar.substring(4));
        
   }
}

Leave a Comment