Java program to get sub string from a given string

Here, we will learn how to get sub string from a given string using String.substring() method in Java? This method returns sub string from given start to end index.

String.substring()

This method is a predefined (built-in) method of String class, its returns sub string (a part of string) from given start to end index.

Syntax:

String.substring(int start_index, int end_index);

Here, start_index is the start index from where we have to get the string. end_index is the end index.

Consider the program:

Given string, start index and end index and we have to get the substring from the string.

import java.util.*;

class getSubstring
{
	public static void main(String args[]) throws Exception
	{
		Scanner sc=new Scanner(System.in);
		String str="";
		
		int startIndex,endIndex;

		//input string 
		System.out.print("Enter the string: ");
		str=sc.nextLine();
		
		//input start index and end index
		System.out.print("Enter start index: ");
		startIndex=sc.nextInt();
		System.out.print("Enter end index: ");
		endIndex=sc.nextInt();

		/*get string from startIndex to endIndex*/
		String temp;
		temp= str.substring(startIndex, endIndex);
		//printing substring
		System.out.println("Substring is: "+temp);
	}
}

Output

Complie: javac getSubstring.java
Run: java getSubstring

Output

First Run:
Enter the string: www.includehelp.com
Enter start index: 2
Enter end index: 6
Substring is: .inc

Second Run:
Enter the string: www.includehelp.com
Enter start index: 0
Enter end index: 10
Substring is: www.includ

Java String Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.