java string substring program

Java String substring() example program

In this tutorial let’s use Java String substring() method to solve a given problem. In this Java String substring() example program we are going to print a substring of all characters in the inclusive range from start to end-1.

Java String substring() example problem

java string substring program

Let’s say “S” is the given string and two indices “start” and “end“. And you need to print substring starting from start to end-1. Below is the java program to achieve the same.

For instance, the following is the sample input and output required to be tested with the program.

Sample Input

Helloworld
3            //start
6            //end

Sample Output

low

Solution: Java String substring()

Below is the Java String substring sample program for the above given requirement.

package com.sneppets.programming;

import java.util.*;

public class SubstringDemo {

	public static void main (String[] args) {
		
		Scanner in = new Scanner(System.in);
		System.out.println("Please enter a string S = ");
		String S = in.next();
		
		System.out.println("Please enter value for index start");
		int start = in.nextInt();
		
		System.out.println("Please enter value for index end");
		int end = in.nextInt();
		System.out.println(S.substring(start,end));
	}
}

Output

Please enter a string S = 
Helloworld
Please enter value for index start
3
Please enter value for index end
6
low

substring()

Note,  java string substring() method returns a part of the string i.e., substring.  And when you pass “start” and “end” indices as arguments to the substring method, it includes start index but end index is exclusive. Hence the end index value “o” is not included in the resulted substring.

Syntax:

public String substring(int beginIndex, int endIndex)

Parameters:

beginIndex - the beginning index, inclusive.

endIndex   - the ending index, exclusive.

The substring method of String class returns a new string i.e., substring of the given string. The substring begins at the specified beginIndex and extends till the character at index endIndex – 1. Therefore does not include the character at index endIndex.

Therefore, you can say the length of the substring is nothing but endIndex-beginIndex.

You’ll also like:

References:

 

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments