Write a java program to Reverse SubString

Given a string, startIndex and length, write a program to extract the substring from right to left. Assume the last character has an index of 0.

The 1st argument corresponds to the string, the second argument corresponds to the startIndex and the third argument corresponds to the length.

Input and Output Format

  • The first line of the input consists of a string.
  • The second line of the input consists of an integer that corresponds to the startIndex.
  • The third line of the input consists of an integer that corresponds to the length of the substring.

Sample Input:

rajasthan

2

3

Sample Output:

hts

Program to Reverse SubString in Java

Following are the steps to reverse substring:

  • Input string, start index, and length of the string from the user.
  • Pass them to retrieveString() method.
  • Inside the method, Create an instance of string buffer with the input string. Call the reverse() method to reverse the input string.
  • Now pass the string, start index+length to the substring() method and get the output string.
  • At last, return the resultant string to the user.
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String input1 = sc.nextLine();
    int input2 = sc.nextInt();
    int input3 = sc.nextInt();
    System.out.println(retrieveString(input1, input2, input3));
  }

  public static String retrieveString(String input1, int input2, int input3) {
    StringBuffer sb = new StringBuffer(input1);
    sb.reverse();
    String output = sb.substring(input2, input2 + input3);
    return output;
  }
}

Output

Thus, in this way, we learn how to find the reverse of a substring in Java.