string.lastIndexOf()

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

Java String lastIndexOf()

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.

Using string and startPos
String my_str="Welcome to plus2net.com";
System.out.println(my_str.lastIndexOf("co",3));// 3
System.out.println(my_str.lastIndexOf("co",2));// -1
System.out.println(my_str.lastIndexOf("com",4));// 3
System.out.println(my_str.lastIndexOf("com",3));// 3
System.out.println(my_str.lastIndexOf("c",2));// -1
System.out.println(my_str.lastIndexOf("c",3));// 3
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.
System.out.println("userid@example.com".lastIndexOf("@",6));// 6
System.out.println("userid@example.com".lastIndexOf("."));// 14
Change the startPos in first line of above code to 5 ( from 6 ) and check the result.

Difference between indexOf() and lastIndexOf()

These pictures shows the difference between indexOf() and lastIndexOf()

Java String indexOf()


Java String lastIndexOf()

All String functions

Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2021 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer