Java Program to search for last index of a group of characters


Use the lastIndexOf() method to search for last index of a group of characters. Let’s say the following is our string.

String myStr = "pqrstuvwxyzpqrst";

Searching for the substring “pqrs” in the string to get the last index of its occurring in the string. We begin the search from index 3.

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

The following is an example, wherein we are searching for the last index of the substring “pqrs”

Example

 Live Demo

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

Output

String: pqrstuvwxyzpqrst
The last index of substring pqrs in the string pqrstuvwxyzpqrst = 11

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements