Advertisement



< Prev
Next >



substring() method




As the name of the method hints, substring() method of String class is used to extract a substring out of an invoked String object, starting at a particular index. There are two forms of substring() method, let's discuss each of those with example one by one.




Signature of the first form of substring() method


public String substring(int startIndex)






Note :


The startIndex int value is a zero-based index, hence the first index is counted as 0.




substring(int startIndex) example


Here in program below, we have a String object and we are extracting a substring out of it by calling the first form of substring() method i.e. substring(int startIndex) method.

// Program to find a substring of a String, starting at a specific index.


class StringSubstring
{
public static void main(String[] ar)
{
String str1= new String("0123456789");

String substring  = str1.substring(2);

System.out.println("Original String is "+ str1);
System.out.println("Substring from index 2 to the end :"+ substring );
}
}

Output is :


Original String is 0123456789
Substring from index 2 to the end :23456789


Program Analysis




Note: Because startIndex is an zero-based index int value, that's why the first index of a string is counted as 0.


Advertisement




Signature of the second form of substring() method


 public String substring(int startIndex, int endIndex)

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement