C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Info: As with indexOf, lastIndexOf can accept a String and a starting index as arguments. It mirrors indexOf in these ways.
StringsHere: We find the last "s" in the string "spins." But the character "x" is not present in the string.
Java program that uses lastIndexOf
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);
}
}
Output
4
-1
Argument 1: This is the string (or character) we are searching for in the source string.
Argument 2: This is the starting position. With lastIndexOf we begin searching from this index to the left.
Tip: At the end of the while-loop we must decrement the index variable i to continue searching the string to the left.
Java program that uses lastIndexOf in while-loop
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--;
}
}
}
Output
cat
cat;cat
cat cat;cat
Version 1: This code calls the indexOf method, so it searches for the char 8 from the start of the string.
Version 2: This version of the code uses lastIndexOf, so it searches for the char from the string's end instead.
Result: If, based on our data, we find that the value occurs near the end more often, lastIndexOf is a faster yet equal method.
Java program that times indexOf, lastIndexOf
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);
}
}
Output
41 ms, indexOf
14 ms, lastIndexOf