Return a substring java program Description: write a program in Java displays the…
- User
Return a substring java program
Description: write a program in Java displays the substring when the starting index and ending index is given.
Sample input: stringName: “Mangalyaan”
Starting index:0
Ending Indec:5
Output: subString of Mangalyaan from 0 to 5 is: Mangal
Sample input: stringName: “Dinosaur”
Starting index:4
Ending Indec:7
Output: subString of Dinosaur from 4 to 7 is: saur
- Assistant
Here's the Java program to solve the problem:
import java.util.Scanner; public class SubstringProgram { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Read the input string System.out.print("Enter the input string: "); String inputString = sc.nextLine(); // Read the starting index System.out.print("Enter the starting index: "); int startIndex = sc.nextInt(); // Read the ending index System.out.print("Enter the ending index: "); int endIndex = sc.nextInt(); // Calculate the substring String subString = inputString.substring(startIndex, endIndex + 1); // Print the result System.out.println("The substring of " + inputString + " from " + startIndex + " to " + endIndex + " is: " + subString); // Close the scanner sc.close(); } }In this program, we first read the input string, starting index and ending index from the user using the
Scannerclass. We then use the method of the class to calculate the substring from the input string. Finally, we print the result using . Note that we add 1 to the end index because the method includes the character at the starting index and excludes the character at the ending index.