Search Your Topic

config
Monday, 24 July 2017 04:11

Substring in Java

Written by
Rate this item
(0 votes)

A part of string is called substring. In other words, substring is a subset of another string. In case of substring startIndex is inclusive and endIndex is exclusive.

Note: Index starts from 0.

You can get substring from the given string object by one of the two methods:

  1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
  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.

In case of string:

  • startIndex: inclusive
  • endIndex: exclusive

Let's understand the startIndex and endIndex by the code given below.

 
  1. String s="hello";  
  2. System.out.println(s.substring(0,2));//he  

In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example of java substring

 
  1. public class TestSubstring{  
  2.  public static void main(String args[]){  
  3.    String s="SachinTendulkar";  
  4.    System.out.println(s.substring(6));//Tendulkar  
  5.    System.out.println(s.substring(0,6));//Sachin  
  6.  }  
  7. }  
Tendulkar
Sachin
Read 166 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.

Java Training

Facebook