1

Test Code

public class HelloWorld{
     public static void main(String []args){
        System.out.println("Hello World".lastIndexOf(' '));
        System.out.println("Hello World".lastIndexOf(' ', 1));
        System.out.println("Hello World".lastIndexOf('e'));
        System.out.println("Hello World".lastIndexOf('e', 1));
     }
}

Result

5
-1
1
1

I expected the second result be 5 but it is -1. How can the first one is right but the second is wrong?

Joshua
  • 5,901
  • 2
  • 32
  • 52
  • Checkout Documentation : @return the index of the last occurrence of the character in the * character sequence represented by this object that is less * than or equal to {@code fromIndex}, or {@code -1} * if the character does not occur before that point. – Abhishek Jun 27 '17 at 09:02
  • From the javadoc : " if no such character occurs in this string _at or before_ position _fromIndex_, then -1 is returned." . – Arnaud Jun 27 '17 at 09:02
  • 1
    Thx guys. I know -1 is not found but I didn't notice if right to left. The variable named fromIndex confused me and I assume it search the substring of start from fromIndex. – Joshua Jun 27 '17 at 09:10

2 Answers2

2

lastIndexOf() goes from right to left, so when it starts with index 1 (the second character, namely 'e'), it does not find a space (which has index 5).

Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72
2

Simplest Way

lastIndexOf(int ch, int fromIndex) returns index of ch only if it occurs at or before fromIndex, Otherwise return -1.

System.out.println("Hello World".lastIndexOf(' ', 3));

returns -1.

System.out.println("He llo World".lastIndexOf(' ', 3));

returns 2.

Abhishek
  • 3,348
  • 3
  • 15
  • 34