Java - Write code to get nth Last Index Of

Requirements

Write code to get nth Last Index Of

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        char c = 'o';
        int n = 2;
        System.out.println(nthLastIndexOf(str, c, n));
    }/*from w w w.j a va2s .co m*/

    public static int nthLastIndexOf(String str, char c, int n) {
        if (str == null) {
            return -1;
        }
        int pos = str.lastIndexOf(c);
        while (n-- > 0 && pos != -1) {
            pos = str.lastIndexOf(c, pos - 1);
        }
        return pos;
    }
}