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
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?
No comments:
Post a Comment