1.

What is the use of the substring() method in Java?

Answer»

The substring method is used to RETURN substring from a SPECIFIED string. This method takes TWO parameters i.e., beginIndex (the starting index) and endIndex (the ending index). In the case of substring(), method startIndex is inclusive and endIndex is exclusive.

Syntax: 

substring(int beginIndex, int endIndex)

Or

substring(int beginIndex)

Here, 

  • beginIndex: Index that marks the starting of subsequence and it is inclusive.
  • endIndex: Index that marks the ending of subsequence and it is exclusive.

Example:

IMPORT java.lang.Math;public class InterviewBit{ // driver code public static void main(String args[]) { String str = "Scaler by InterviewBit"; //prints substring from 7th index System.out.print("Returns: "); System.out.println(str.substring(7)); // prints substring from 0-6, exclusive 6TH index System.out.print("Returns: "); System.out.println(str.substring(0, 6)); // prints the substring from 10-22, exclusive 22th index System.out.print("Returns: "); System.out.println(str.substring(10, 22)); } }

Output: 

Returns: by InterviewBitReturns: ScalerReturns: InterviewBit


Discussion

No Comment Found