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

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

ordinalIndexOf(s, ss, 0) is equivalent to s.indexOf(ss)

ordinalIndexOf(s, ss, 1) is equivalent to s.indexOf(ss, s.indexOf(ss) + 1)

and so on...

Example input / output

Expression Result Explanation
ordinalIndexOf("abcd abcd", "bc", 0) 1 The 0th occurrence is found at index 1
ordinalIndexOf("abcd abcd", "bc", 1) 6 The 1st (zero-based) occurrence is found at index 6
ordinalIndexOf("abcd abcd", "bc", 2) -1 There's no 2nd (zero-based) occurrence, hence -1 is returned
ordinalIndexOf("aaaaa", "aaa", 1) 1 Matches may overlap

Apache Commons Lang

See StringUtils.ordinalIndexOf

Comments (3)

User avatar

Thanks, this was exactly what I wanted!

by Daniel |  Reply
User avatar

This is resulting in -1

by Ritu |  Reply
User avatar

-1 indicates that the n:th (zero-based!) occurrence wasn't found. For example ordinalIndexOf("abab", "ab", 10) returns -1.

by Andreas Lundblad |  Reply

Add comment