Tuesday 2 November 2021

Java: Get the index of last occurrence of a substring

Using ‘lastIndex’ method we can get the index of last occurrence of a substring.

 

public int lastIndexOf(String str)

Returns the index within this string of the last occurrence of the specified substring, or -1 if there is no such occurrence.

 

LastIndexDemo.java

package com.sample.app.strings;

public class LastIndexDemo {

	public static void main(String args[]) {
		String str = "abrakadabra";

		int brLastIndex = str.lastIndexOf("br");
		int xyLastIndex = str.lastIndexOf("xy");

		System.out.println("str -> " + str);
		System.out.println("brLastIndex " + brLastIndex);
		System.out.println("xyLastIndex -> " + xyLastIndex);
	}

}

 

Output

str -> abrakadabra
brLastIndex 8
xyLastIndex -> -1

 

Reference

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#lastIndexOf-java.lang.String-

 

 

  

You may like

Interview Questions

How to call a method asynchronously in Java?

How method overloading works with null values in Java?

Java: How to find maximum element in a collection?

Java: How to find the minimum element in a collection?

Java: Get the index of first occurrence of a substring

No comments:

Post a Comment