I cant understand this lastindexof method in Java 11- version2

115 Views Asked by At
public class Test2{
public static void main(String[] args) {

    String str="this is how";

    int a0=str.lastIndexOf("is");

    int a=str.lastIndexOf("is",0);
    int b=str.lastIndexOf("is",1);
    int c=str.lastIndexOf("is",2);
    int d=str.lastIndexOf("is",3);
    int e=str.lastIndexOf("is",4);
    int f=str.lastIndexOf("is",5);




    int b1=str.lastIndexOf("is",-1);
    int c1=str.lastIndexOf("is",-2);
    int d1=str.lastIndexOf("is",-3);
    int e1=str.lastIndexOf("is",-4);
    int f1=str.lastIndexOf("is",-5);

    System.out.println("Last index of from index 0 "+a0);

    System.out.println("Last index of from index 0 "+a);
    System.out.println("Last index of from index 1 "+b);
    System.out.println("Last index of from index 2 "+c);
    System.out.println("Last index of from index 3 "+d);
    System.out.println("Last index of from index 4 "+a);
    System.out.println("Last index of from index 5 "+f);
    System.out.println("Last index of from index -1 "+b1);
    System.out.println("Last index of from index -2 "+c1);
    System.out.println("Last index of from index -3 "+d1);
    System.out.println("Last index of from index -4 "+e1);
    System.out.println("Last index of from index -5 "+f1);
}

}

Results

Last index of from index 0 5
Last index of from index 0 -1
Last index of from index 1 -1
Last index of from index 2 2
Last index of from index 3 2
Last index of from index 4 -1
Last index of from index 5 5
Last index of from index -1 -1
Last index of from index -2 -1
Last index of from index -3 -1
Last index of from index -4 -1
Last index of from index -5 -1
1

There are 1 best solutions below

3
On

int lastIndexOf(str, fromIndex): Returns the last occurrence of str, starts searching backward from the specified index “fromIndex”.

Example:

String char1 = 't';
String str = "test";

int index = str.lastIndexOf(char1); // Will return index = 3
int index_b = str.lastIndexOf(char1, 2) //Will start search backwards from letter 's' and return index_b = 0 

It's well documented here