Table of contents
Given a string,s, and two indices,start and end, print a substring consisting of all characters in the inclusive range from start to end - 1. You'll find the String class' substring method helpful in completing this challenge.
Input Format
The first line contains a single string denoting s.
The second line contains two space-separated integers denoting the respective values of start and end.
Constraints
1 <= |s| <= 100
0 <= start < end <= n
string s consists of English alphabetic letters (i.e.,[a-zA-Z ) only.
Output Format
Print the substring in the inclusive range from start to end-1.
Sample Input
Helloworld
3 7
Sample Output
lowo
Explanation
In the diagram below, the substring is highlighted in green:
Solution:
Language: Java
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String S = s.next();
int start = s.nextInt();
int end = s.nextInt();
System.out.println(S.substring(start,end));
}
}
What Is Substring in java ?
A part of a String is called a substring. In other words, a substring is a subset of another String. Java String class provides the built-in substring() method that extracts a substring from the given string by using the index values passed as an argument. In the case of substring() method startIndex is inclusive
and endIndex is exclusive.
Suppose the string is "navnath", then the substring will be nav
, nath
, vna
etc.
You can get a substring from the given String object by one of the two methods:
1) public String substring(int startIndex):
This method returns a new String object containing the substring of the given string from the specified startIndex (inclusive). The method throws an IndexOutOfBoundException
when the startIndex is larger than the length of the String or less than zero.
2) public String substring(int startIndex, int endIndex):
This method returns a new String object containing the substring of the given string from specified startIndex to endIndex. The method throws an IndexOutOfBoundException
when the startIndex is less than zero or startIndex is greater than the endIndex or the endIndex is greater than the length of String
For Example:
Input:
public class navnath
{
public static void main(String args[])
{
String s="NavnathJadhav";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 7: " +s.substring(7));
System.out.println("Substring starting from index 0 to 7: "+s.substring(0,7));
}
}
Output:
Original String: NavnathJadhav
Substring starting from index 7: Jadhav
Substring starting from index 0 to 7: Navnath