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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 12-Dec-2018 14:51:55
Advertisements