public static int nthIndex(String s, char ch, int n) {
    int index = 0;
    for (int i = 0; i < n; i++) {
      // if we're already at the end of the string,
      // and we need to find another ch, return -1
      if (index == s.length() - 1) {
        return -1;
      }
      index = s.indexOf(ch, index + 1);
      if (index == -1) {
        return (-1);
      }
    }
    return index;
  }
public static int nthIndex ( String s , char ch , int n ) { int index = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( index == s . length ( ) - 1 ) { return - 1 ; } index = s . indexOf ( ch , index + 1 ) ; if ( index == - 1 ) { return ( - 1 ) ; } } return index ; }
Returns the index of the <i>n</i>th occurrence of ch in s, or -1
if there are less than n occurrences of ch.