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

后端 未结 5 2111
南旧
南旧 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:33

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

提交回复
热议问题