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

后端 未结 5 2118
南旧
南旧 2021-01-13 10:48

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

5条回答
  •  日久生厌
    2021-01-13 11:38

    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));
    }
    

提交回复
热议问题