string.lastIndexOf() Returns the position of the matching string or char from right.
Syntax
string.lastIndexOf(input,startPos)
input : Can be char or string. startPos : (optional ) Int postion from where the matching will start
Note these points
Matching position is always returned from left, first position is 0 ( zero ).
Last occurrence is returned ( Up to startPos index, if given ) .
Search starts from end of the string if startPos is not given.
Returned value is always less than or equal to startPos.
Using char input
String my_str="Welcome to plus2net.com";
System.out.println(my_str.lastIndexOf("2"));// 15
System.out.println(my_str.lastIndexOf("e"));// 17
System.out.println(my_str.lastIndexOf("o"));// 21
Using char and startPos
String my_str="Welcome to plus2net.com";
System.out.println(my_str.lastIndexOf("o",20));// 9
System.out.println(my_str.lastIndexOf("o",5));// 4
Check the difference in values of above two lines. In the last line since the value of startPos is reduced to 5 so the search starts from 5 and o is available at position number 4 ( o at position 9 is excluded from the search in last line ) .
Using string input
String my_str="Welcome to plus2net.com";
System.out.println(my_str.lastIndexOf("co"));// 20
There are more than one co present inside the string. Here search is started from end so 20th position is returned.
We will get output as -1 when no matching is found. All matchings are done within the startPos , that is the reason why we are getting -1 when we are searching for co with startPos=2.
Getting position of @ and . inside a email address.