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

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

    Working further on https://stackoverflow.com/a/5678546/15789 and https://stackoverflow.com/a/14356988/15789 (Thanks to original posters @sebastiaan-van-den-broek and @assylias).

    Get all the indices in an array. Then you can get any nth index. In many cases, it may be required to get the nth index of a substring within a string multiple number of times. Getting an array once and accessing it multiple times may be easier.

    public static int[] getIndices(String source, String substr) {
        List indicesList = null;
        int index = source.indexOf(substr);
        if (index == -1) {
            return new int[0];
        } else {
            indicesList = new ArrayList<>();
            indicesList.add(index);
        }
    
        while (index != -1) {
            index = source.indexOf(substr, index + 1);
            if (index != -1) {
                indicesList.add(index);
            }
        }
    
        // Integer[] iarr = new int[1]; 
        //Autoboxing does not work with arrays. Run loop to convert. 
        //toArray does not convert Integer[] to int[]
        int[] indices = new int[indicesList.size()];
        for (int i = 0; i < indicesList.size(); i++) {
            indices[i] = indicesList.get(i);
        }
        return indices;
    }
    

提交回复
热议问题