java

How to extract a substring from a string in Java

In this tutorial, we are going to see how to extract a substring from a string in java.

The substring(int start, int end) method of the String class. It returns a new string which is a substring of this string. The substring begins at the specified “start” index and extends to the character at index “end – 1”. So the length of the substring = end – start.
 

How to extract a substring from a string in Java
import java.lang.*;

public class Main {
   public static void main(String[] args) {
      String str = "Hello, welcome to StackHowTo!";
      String res = "";

      res = str.substring(18, 29);
      System.out.println("The substring is : " + res);

      res = str.substring(0, 5);
      System.out.println("The substring is : " + res);
   }
}

Output:

The substring is : StackHowTo
The substring is : Hello
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *