Java Program to search for a Substring from a specified index


Use the indexOf() method to search for a substring from a given position.

Let’s say the following is our string.

String myStr = " pqrstuvwxyzpqrst";

Searching for the substring “pqrs” in the string. We are beginning the index from 3 for our search.

int begnIndex = 3;
strLastIndex = myStr.indexOf("pqrs", begnIndex);

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String myStr = "pqrstuvwxyzpqrst";
       int strLastIndex = 0;
       int begnIndex = 3;
       System.out.println("String: "+myStr);
       strLastIndex = myStr.indexOf("pqrs", begnIndex);
       System.out.println("The index of substring pqrs in the string beginning from index "+begnIndex+" = "+strLastIndex);
    }
}

Output

String: pqrstuvwxyzpqrst
The index of substring pqrs in the string beginning from index 3 = 11

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

230 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements