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

The basic logic is to run a loop Construct from <index1> to <index2 – 1> position and simultaneously accumulate characters in a String Variable.

Code:

/* Program to enter a string and extract its Substring*/
import java.util.*;
class SubString
{
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="";
char c;
for(i=st;i<en;i++)
{
c=s.charAt(i);
z=z+c;
}

System.out.println("Extracted Substring: "+z);

}
}

Output:

Enter String: ALMOST

 Enter Starting Index: 2

 Enter Ending Index: 5
Extracted Substring: MOS

Report Error/ Suggestion

Related Posts:

[yuzo_views]











CopyRight © 2019

CopyRight © 2019