Q:

Java program to get sub string from a given string

belongs to collection: Java String Programs

0

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.

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.nerdutella.com
Enter start index: 0
Enter end index: 10
Substring is: www.nerdut

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to convert any type of value to strin... >>
<< Java program to convert string to lowercase and up...