find the nth index of a char c in a string. returns -1 if there aren't that many chars in the string - Android java.lang

Android examples for java.lang:String Search

Description

find the nth index of a char c in a string. returns -1 if there aren't that many chars in the string

Demo Code

import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Main{

    /**/*  www  . j av a2  s  .co  m*/
     * 
     * @param c
     * @param n
     * @return
     */
    public static int getNthIndexOf(char c, String str, int n) {

        if (n < 1) {
            throw new IllegalArgumentException("n must be >= 1: " + n);
        }

        int index = str.indexOf(c);
        int count = 0;
        while (index != -1 && (++count) < n) {
            index = str.indexOf(c, index + 1);
        }

        return index;
    }

}

Related Tutorials