Java Program to Get Sub String From a Given String

You are currently viewing Java Program to Get Sub String From a Given String

Java program to get sub string from a given 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

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply