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 . Does anyone have any suggesti
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));
}