Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find the nth occurence of a substring in a string in java?

I have a string that is the complete content of an html page and I am trying to find the index of 2nd occurence of </table>. Does anyone have any suggestions on how to achieve this?

like image 599
TKV Avatar asked Apr 15 '11 14:04

TKV


2 Answers

A generalization of @BasVanDenBroek's answer, using indexOf:

public static int nthIndexOf(String source, String sought, int n) {
    int index = source.indexOf(sought);
    if (index == -1) return -1;

    for (int i = 1; i < n; i++) {
        index = source.indexOf(sought, index + 1);
        if (index == -1) return -1;
    }
    return index;
}

Quick and dirty test:

public static void main(String[] args) throws InterruptedException {
    System.out.println(nthIndexOf("abc abc abc", "abc", 1));
    System.out.println(nthIndexOf("abc abc abc", "abc", 2));
    System.out.println(nthIndexOf("abcabcabc", "abc", 2));
    System.out.println(nthIndexOf("abcabcabc", "abc", 3));
    System.out.println(nthIndexOf("abc abc abc", "abc", 3));
    System.out.println(nthIndexOf("abc abc defasabc", "abc", 3));
    System.out.println(nthIndexOf("abc abc defasabc", "abc", 4));
}
like image 97
assylias Avatar answered Sep 30 '22 06:09

assylias


Here is a shot for fun ;)

public static int findNthIndexOf (String str, String needle, int occurence)
            throws IndexOutOfBoundsException {
    int index = -1;
    Pattern p = Pattern.compile(needle, Pattern.MULTILINE);
    Matcher m = p.matcher(str);
    while(m.find()) {
        if (--occurence == 0) {
            index = m.start();
            break;
        }
    }
    if (index < 0) throw new IndexOutOfBoundsException();
    return index;
}
like image 31
John Giotta Avatar answered Sep 30 '22 05:09

John Giotta