Taking Substring

Ads
 

Taking Substring

In this example we are taking a sub string from a given string.

In this example we are taking a sub string from a given string.

Taking  Substring

     

In this example we are taking a sub string from a given string. You will learn how to use the substring() method of String class.

In this example we are creating an string object .We initialize this string object as "Rajesh Kumar". We are taking sub string by use of substring()  method.

The substring method is used to get certain part of the String into a new variable.

Here in the program we are creating a new sub string with the help of substring() function of String class.

The methods used:

substring(int i):
This method is used to find all sub string after index i.

substring(int start,int end):

This is used to find the substring between start and end point.

The code of the program is given below:

public class SubstringExample1{
  public static void main(String[] args){
  String string = "Rajesh kumar"
  System.out.println("String : " + string);
  String substring = string.substring(3);
  System.out.println("String after 3rd index:
 " 
+ substring)
  substring = string.substring(12);
  System.out.println("Substring (1,2): " 
substring
);
  }
}

In the above program we are using the substring() method to get certain characters from the big string. Here we are passing the two parameters start index and the end index for extracting the string.

With the help of substring() method of String class you get the desired characters from a big String. In general Java programming this method is very useful while processing string data in any business application.

Advertisement

Here is the Syntax of substring() method of the String class:

public String substring(int beginIndex)

or

public String substring(int beginIndex, int endIndex)

The substring() method takes two parameters a) begin index and b) the end index.

The output of the program is given below:

C:\convert\rajesh\completed>javac SubstringExample1.java
C:\convert\rajesh\completed>java SubstringExample1
String : Rajesh kumar
String after 3rd index: esh kumar
Substring (1,2): a

Download this example.

Ads

Ads