Java substring
In the last topic we have learnt about comparison of two strings and different ways of comparing strings. In this topic we are going to see finding out the substring in Java.
Java Substring : Method 1
In order to get substring from the given string we have following two methods provided by String Class of Java.
public String substring(int startIndex);
This method returns new String object containing the substring of the given string from specified startIndex.
class SubString{ public static void main(String args[]){ String str1 = "c4learn.com"; String str2 = "c4learn.com"; System.out.println(str1.substring(0)); System.out.println(str1.substring(8)); System.out.println(str1.substring(2)); } }
Output :
c4learn.com com learn.com
Java Substring : Method 2
public String substring(int startIndex,int endIndex);
This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
class SubString{ public static void main(String args[]){ String str1 = "c4learn.com"; System.out.println(str1.substring(0,2)); System.out.println(str1.substring(3,6)); System.out.println(str1.substring(2,8)); } }
Output :
c4 ear learn.
Explanation :
str1.substring(0,2)
It will include all the characters from 0 to 2 excluding the endIndex. i.e (0,1 will be included only and 2 will be excluded)