String字符串中获取所有匹配结果的索引值

String字符串中获取所有匹配结果的索引值

例如现在我们有这样一段代码


public interface ActErrorHisMapper {

    public List getPage(Map params);

    public List getList(Map params);

    public int getCount(Map params);
}

我们要查找所有的public关键字出现的索引,那么可以这么写

    public static List findAllIndex(String string,int index,String findStr){
        List list =new ArrayList<>();
        if (index != -1){
            int num = string.indexOf(findStr,index);
            list.add(num);
            //递归进行查找
            List myList = findAllIndex(string,string.indexOf(findStr,num+1),findStr);
            list.addAll(myList);
        }
        return list;
    }

这样调用即可

    public static void main(String[] args) {
        String string = "public interface ActErrorHisMapper {\n" + "\n"
                + "    public List getPage(Map params);\n" + "\n"
                + "    public List getList(Map params);\n" + "\n"
                + "    public int getCount(Map params);\n" + "}";
        List num = findAllIndex(string,0,"public");
        for (Integer integer : num){
            System.out.println(integer);
        }
    }

输出结果如下:

0
42
106
170

你可能感兴趣的:(String字符串中获取所有匹配结果的索引值)