Java String lastIndexOf() method
Java String lastIndexOf() method returns last index of character or substring in a String.
Syntax:
Method Description
| int lastIndexOf(int ch) | It returns last index position for the given char value |
| int lastIndexOf(int ch, int fromIndex) | It returns last index position for the given char value and from index |
| int lastIndexOf(String substring) | It returns last index position for the given substring |
| int lastIndexOf(String substring, int fromIndex) | It returns last index position for the given substring and from index |
Parameter
ch : a single character
fromIndex : index position from where index of the char value or substring is returned
substring : substring to be searched in current String
Returns
It returns last index of the given String
Java String lastIndexOf() method example
public class JavaStringLastIndexOfEx1
{
public static void main(String args[])
{
String s1="Java String Last IndexOf method Examples";//there are 2 's' characters in this sentence
int index1=s1.lastIndexOf('s');//returns last index of 's' char value
int index2=s1.indexOf('s');
System.out.println("Last index : "+index1);//39
System.out.println("Index :"+index2);//14
}
}
Output:
Last index : 39 Index :14
Java String lastIndexOf(int ch, int fromIndex) method example
public class JavaStringLastIndexOfEx2 {
public static void main(String[] args) {
String s1="Java String Last IndexOf method Examples";
int index = s1.lastIndexOf('a',7);
System.out.println(index);
}
}
Output:
3
Java String lastIndexOf(String substring) method example
public class JavaStringLastIndexOfEx3
{
public static void main(String[] args)
{
String str = "Java String Last IndexOf method Examples";
int index = str.lastIndexOf("method");
System.out.println(index);
}
}
Output:
25
Java String lastIndexOf(String substring, int fromIndex) method example
public class JavaStringLastIndexOfEx4
{
public static void main(String[] args)
{
String str = "Java String Last IndexOf method Examples";
int index = str.lastIndexOf("Of", 25);
System.out.println(index);
index = str.lastIndexOf("Of", 10);
System.out.println(index); // -1, if not found
}
}
Output:
22 -1
