String.lastIndexOf()
Finds the position of the last occurrence of a character or a substring.
Available since: Java 1.0
Syntax
public int lastIndexOf(String str)Parameters
| Parameter | Type | Description |
|---|---|---|
| str | String | What to look for — a string or a char. |
Return value
intThe index of the last occurrence, or -1.
Examples
The last occurrence:
void main() {
IO.println("banana".lastIndexOf('a'));
IO.println("banana".lastIndexOf("an"));
}Output:
5
3A file extension — everything after the last dot:
void main() {
String file = "report.final.pdf";
String ext = file.substring(file.lastIndexOf('.') + 1);
IO.println(ext);
}Output:
pdfNotes
If there is no dot, lastIndexOf('.') returns -1 and substring(0) returns the whole string. Check for -1 when it matters.
See also
- String.indexOf() — Finds the position of the first occurrence of a character or a substring.
- String.substring() — Returns the part of a string between two indexes.
Related recipes
In the tutorial
- String methods — The main String methods in Java: searching, substring, changing case, strip, replace, split, join, repeat and string checks.