Search code examples
javastringlastindexof

Java lastIndexOf always return -1 if the character is space and fromIndex is set


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?


Solution

  • 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).