Java Program to extract Substring using substring() function

Here, we are supposed to enter a String Input and input 2 Integer inputs as index. Using this two indexes, we’ll extract characters from the string.

The basic logic is to use the String Function <String>.substring(<index1>,<index2>);—-this will extract characters from <index1> to <index2 – 1> position and store the result.

Java Code:

/* Program to enter a string and extract its Substring using function*/
import java.util.*;
class FuncSubString
public static void main()
Scanner inp=new Scanner(;
System.out.print("\n Enter String: ");
String s=inp.nextLine();
System.out.print("\n Enter Starting Index: ");
int st=inp.nextInt();
System.out.print("\n Enter Ending Index: ");
int en=inp.nextInt();
if(st<0 || en>(s.length()))
System.out.println("Invalid Index");
int i,k=s.length();
String z=s.substring(st,en);
System.out.println("Extracted Substring: "+z);


Enter String: Titanics

 Enter Starting Index: 0

 Enter Ending Index: 5
Extracted Substring: Titan

Report Error/ Suggestion

Related Posts:

CopyRight © 2020

CopyRight © 2020