Java String.lastIndexOf
Locate the final occurrence of a character or substring, optionally searching backward from an offset.
A simple example
String.lastIndexOf
- Start with "aba", looking for a
- Do this Find the last match
- Result Index 2 (zero-based)
class Main {
public static void main(String[] args) throws Exception {
System.out.println("aba".lastIndexOf("a"));
}
}
2
Syntax
public int lastIndexOf(int ch)
JDK 21 method signatures (4)
public int lastIndexOf(int ch)
public int lastIndexOf(int ch, int fromIndex)
public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaRead the final extension of an invoice
A folder contains active exports alongside files with similar names and additional suffixes. Inspect the final filename or extension carefully before placing an entry in the report.
class Main {
public static void main(String[] args) throws Exception {
String file = "april.invoice.pdf";
System.out.println(file.substring(file.lastIndexOf('.') + 1));
}
}
The final dot separates the extension from the rest of the filename.
Locate the previous stop in a route
A compound filename or route code uses punctuation to separate fields. Decide whether the first or last separator marks the desired boundary before extracting the field next to it.
class Main {
public static void main(String[] args) throws Exception {
String route = "A/B/C/D";
System.out.println(route.lastIndexOf("/", 4));
}
}
3
Backward search from index four finds the slash before C.
Read a parcel sorting code
The depot scans a parcel marked NC-17. Find the dash in this identifier. How many characters precede the matching separator?
What to watch for
A missing match returns -1. Check that result before using it as an index.