Java Program to enter a string and extract its Substring
Written by
In this program, we are asked to enter a string and two integer values as indexes. Using these indexes, we will extract a substring from the string. The substring will be formed by iterating through the string from the starting index to the ending index - 1 and concatenating the characters onto a new string.
The logic for this process is as follows:
- Prompt the user to enter a string and two integer indexes.
- Validate the indexes to ensure they are within the bounds of the string. If the indexes are invalid, display an error message and exit the program.
- Initialize an empty string variable to hold the extracted substring.
- Iterate through the string from the starting index to the ending index - 1, adding each character to the substring variable.
- Display the extracted substring to the user.
Code:
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