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?
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));
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With