Java: Finding the Nth occurrence of a substring in a String

JDK solution:

public static int ordinalIndexOf(String str, String substr, int n) {
    int pos = str.indexOf(substr);
    while (--n > 0 && pos != -1)
        pos = str.indexOf(substr, pos + 1);
    return pos;
}

To find the index of the 1st occurrence of "l" in "Hello" you call ordinalIndexOf("Hello", "l", 1) (which is equivalent to "hello".indexOf("l")). The index of the 2nd occurrence is found by ordinalIndexOf("Hello", "l", 2) and so on.

If you happen to already depend on Apache Commons Lang, use StringUtils.ordinalIndexOf

Comments