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.

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.in);
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");
System.exit(0);
}
int i,k=s.length();
String z=s.substring(st,en);
System.out.println("Extracted Substring: "+z);
}
}

Output:

Enter String: Titanics

 Enter Starting Index: 0

 Enter Ending Index: 5
Extracted Substring: Titan

[yuzo_views]



CopyRight © 2019

CopyRight © 2019