Java lastIndexOf() Method
The lastIndexOf() method has the following four forms:
-
public int lastIndexOf(int ch): Returns the index of the last occurrence of the specified character in this string, or -1 if this string does not contain such a character.
-
public int lastIndexOf(int ch, int fromIndex): Returns the index of the last occurrence of the specified character in this string, searching backward starting from the specified index, or -1 if this string does not contain such a character.
-
public int lastIndexOf(String str): Returns the index of the last occurrence of the specified substring in this string, or -1 if this string does not contain such a substring.
-
public int lastIndexOf(String str, int fromIndex): Returns the index of the last occurrence of the specified substring in this string, searching backward starting from the specified index, or -1 if this string does not contain such a substring.
Syntax
public int lastIndexOf(int ch)
or
public int lastIndexOf(int ch, int fromIndex)
or
public int lastIndexOf(String str)
or
public int lastIndexOf(String str, int fromIndex)
Parameters
-
ch -- A character.
-
fromIndex -- The index to start the search from.
-
str -- The substring to search for.
Return Value
The index of the first occurrence of the specified substring in the string.
Example
public class Test {
public static void main(String args[]) {
String Str = new String("tutorialpro.org:www.tutorialpro.org");
String SubStr1 = new String("tutorialpro");
String SubStr2 = new String("com");
System.out.print("Find the last occurrence of character o: ");
System.out.println(Str.lastIndexOf('o'));
System.out.print("Find the last occurrence of character o starting from index 14: ");
System.out.println(Str.lastIndexOf('o', 14));
System.out.print("Find the last occurrence of substring SubStr1: ");
System.out.println(Str.lastIndexOf(SubStr1));
System.out.print("Find the last occurrence of substring SubStr1 starting from index 15: ");
System.out.println(Str.lastIndexOf(SubStr1, 15));
System.out.print("Find the last occurrence of substring SubStr2: ");
System.out.println(Str.lastIndexOf(SubStr2));
}
}
The output of the above program is:
Find the last occurrence of character o: 17
Find the last occurrence of character o starting from index 14: 13
Find the last occurrence of substring SubStr1: 9
Find the last occurrence of substring SubStr1 starting from index 15: 9
Find the last occurrence of substring SubStr2: 16