LastIndexOf
A string
in Java may contain the letters "abc." But this occurs twice in the string. With lastIndexOf
we search from the rightmost index of a String
.
With an index argument, we begin searching from a certain position in the string. In a while
-loop, we can scan for all occurrences of a string
from the end of the source string
.
This simple example uses the lastIndexOf
method with char
arguments. It locates first the final instance of the char
.
indexOf
, lastIndexOf
can accept a String
and a starting index as arguments. It mirrors indexOf
in these ways.public class Program { public static void main(String[] args) { String line = "spins"; // Get index of last "s." int result1 = line.lastIndexOf('s'); System.out.println(result1); // There is no "x" in the string. // ... This returns negative 1. int result2 = line.lastIndexOf('x'); System.out.println(result2); } }4 -1
Here we call lastIndexOf
with a string
argument in a while
-loop. The lastIndexOf
call locates the last "cat" string
at a starting position.
string
(or character) we are searching for in the source string
.lastIndexOf
we begin searching from this index to the left.while
-loop we must decrement the index variable "i" to continue searching the string
to the left.public class Program { public static void main(String[] args) { // The string we are searching. String line = "cat cat;cat"; // Search from this index (the last index). int i = line.length() - 1; // Continue calling lastIndexOf from the last start position. while ((i = line.lastIndexOf("cat", i)) >= 0) { // The string "cat" was found. // ... It starts at this position. System.out.println(line.substring(i)); // Move to previous index. i--; } } }cat cat;cat cat cat;cat
lastIndexOf
Sometimes we can use lastIndexOf
as an optimization. If a substring occurs 0 or 1 times in a String
, indexOf
and lastIndexOf
return the same result.
indexOf
method, so it searches for the char
8 from the start of the string
.lastIndexOf
, so it searches for the char
from the string
send instead.lastIndexOf
is a faster yet equal method.public class Program { public static void main(String[] args) { String input = "0123456789"; long t1 = System.currentTimeMillis(); // Version 1: use indexOf. for (int i = 0; i < 10000000; i++) { int index = input.indexOf('8'); if (index < 0) { System.out.println(false); } } long t2 = System.currentTimeMillis(); // Version 2: use lastIndexOf. for (int i = 0; i < 10000000; i++) { int index = input.lastIndexOf('8'); if (index < 0) { System.out.println(false); } } long t3 = System.currentTimeMillis(); // ... Times. System.out.println(t2 - t1); System.out.println(t3 - t2); } }41 ms, indexOf 14 ms, lastIndexOf
The lastIndexOf
method searches from the right to the left. It is essentially the same method as indexOf
but with an inverted order of searching.