Tutorials

Java String


Java Substring


When we create subset of a given String then each item in subset is substring of given String.

 

Example:

Given String →“Rajneesh”

Possible Substring{R, Ra, Raj,ajn, eesh, h, ……….}

 

So as long as you are able to break the given String into bits and pieces you get a new substring from the given String. 

 

In java, we have two methods which help us create substring from a given String. They are given below:

 

1.public String substring(int startIndex): This method creates substring of given String considering the specified start index. For example,

StringMukesh Tiwari

startIndex1

Output substringukesh Tiwari

 

Let’s see the code for creating the same substring programmatically.

public class CreateSubstring {

 

      public static void main(String[] args) {

            String str = "Mukesh Tiwari";

            String subStr = str.substring(1); //give index

            System.out.println(subStr);

      }

}

OUTPUT:

ukesh Tiwari

 

TODO: Change the index and try to play with it and see different substring output that you get.

Note:

  • For any String the starting index will be 0. Here M in Mukesh Tiwari is at index 0.
  • Element at the starting index will be included while forming substring.

2.public String substring(int startIndex, int endIndex): This method creates substring of given String considering the specified start index and end index. For example,

StringMukesh Tiwari

startIndex1

endIndex8

Output substringukesh T

 

Let’s see the code for creating the same substring programmatically.

 

public class CreateSubstring {

 

      public static void main(String[] args) {

            String str = "Mukesh Tiwari";

            String subStr = str.substring(1,8);

            System.out.println(subStr);

      }

}

OUTPUT:

ukesh T

 

Note: Element at the starting index will be included and end index will be excluded while forming substring.

 



Please Share this page
Views : 94
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!