Set a Range for Displaying Substring in Java



In this article, we'll learn how to extract a specific range of characters from a string in Java using the substring() method. The substring(int beginIndex, int endIndex) method gets a part of a string from the beginIndex to just before the endIndex.

Problem Statement

Given a string, extract a substring from a specified range of indices.

Input

String: pqrstuvw

Output

Substring: stu

Steps to set a range for displaying substring

Following are the steps to set a range for displaying substring ?

  • Declare a string str.
  • Initialize the string str with the value "pqrstuvw".
  • Use the substring(int beginIndex, int endIndex) method to extract characters from the index.
  • Print the output

Java program to set a range for displaying substring

The following is the complete example wherein we have set a range for displaying substring from a string ?

public class Demo {
    public static void main(String[] args) {
       String str = "pqrstuvw";
       System.out.println("String: "+str);
       // range from 3 to 6
       String strRange = str.substring(3, 6);
       System.out.println("Substring: "+strRange);
    }
}

Output

String: pqrstuvw
Substring: stu

Code Explanation

In the code, we will use the substring() method to set a range of substrings from a string. Let's say the following is our string ?

String str = "pqrstuvw";

The str.substring(3, 6) picks characters from position 3 to 5 in the string "pqrstuvw".

String strRange = str.substring(3, 6);

This gives the substring stu, which is saved in strRange. The main() method then prints the original string and the extracted substring. 

Updated on: 2024-08-19T18:33:51+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements