The lastIndexOf() method in Java is a method of the String class. It is used to find the last occurrence (the rightmost occurrence) of a specified character or substring in a given string.
Find the last occurrence of a specified character
Syntax:
public int lastIndexOf(int ch)
int ch – A character (specified by its Unicode value) to search for.
Example:
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello World!";
// Find the last occurrence of the character 'o'
int index = str.lastIndexOf('o');
System.out.println("Last index of 'o': " + index);
}
}
Output: Last index of ‘o’: 7
Notes:
- The method returns the index of the last occurrence of the specified character or substring.
- If the character or substring is not found, it returns -1.
Find the last occurrence of a specified string
Syntax:
public int lastIndexOf(String str)
Example:
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello World Hello";
// Find the last occurrence of the substring "Hello"
int index = str.lastIndexOf("Hello");
System.out.println("Last index of 'Hello': " + index);
}
}
Output: Last index of ‘Hello’: 12
Find the string not found
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello World";
// Find the last occurrence of the substring "Java"
int index = str.lastIndexOf("Java");
System.out.println("Last index of 'Java': " + index);
}
}
Output: Last index of ‘Java’: -1
Find lastIndexOf() with a starting index
You can also specify a starting index from which the search will begin (searching backward).
public class LastIndexOfExample {
public static void main(String[] args) {
String str = "Hello World Hello";
// Start search from index 5
int index = str.lastIndexOf("Hello", 5);
System.out.println("Last index of 'Hello' before index 5: " + index);
}
}