Thursday, 2 February 2017

SUBSTRING IN JAVA

A part of a string is known as sub-string. In substring the start index is always inclusive and the end index is exclusive, which means the start index which we counts start with 0 but when we count for end index, it takes into consideration start index as 1 and moves till the end index. There are 2 two ways in which we can find the substring of a given string.

1. public String substring( int Startindex)

Example –
public class String1 {
          public static void main(String[] args) {
                   String s1="hello java";
                   System.out.println(s1.substring(6));
          }
}

Output –
Java

Note – In the above example the start index is 6 so counting the first index as 0 counter moves till index 6 and prints from there the remaining strings.


2. public String substring(int startindex, int endindex)

Example –
public class String1 {
          public static void main(String[] args) {
                   String s1="hello java";
                   System.out.println(s1.substring(0,8));
          }
}

Output –
hello ja


Note – In the above example the start index which is inclusive starts from 0 , but the end index which is exclusive so it starts from 1 and moves till 8th index and prints the value.

No comments:

Post a Comment