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

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

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


public interface ActErrorHisMapper {

    public List<ActError> getPage(Map<String, Object> params);

    public List<ActError> getList(Map<String, Object> params);

    public int getCount(Map<String, Object> params);
}

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

    public static List<Integer> findAllIndex(String string,int index,String findStr){
        List<Integer> 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<ActError> getPage(Map<String, Object> params);\n" + "\n"
                + "    public List<ActError> getList(Map<String, Object> params);\n" + "\n"
                + "    public int getCount(Map<String, Object> params);\n" + "}";
        List<Integer> num = findAllIndex(string,0,"public");
        for (Integer integer : num){
            System.out.println(integer);
        }
    }

输出结果如下:

0
42
106
170

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前言 最先接触编程的知识是在大学里面,大学里面学了一些基础的知识,c语言,java语言,单片机的汇编语言等;大学毕...
    oceanfive阅读 3,553评论 0赞 7
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,446评论 19赞 139
  • 近朱者赤,近墨者黑。这句话出自《太子少傅箴》中,它形容环境对人的影响。也可以形容友情的友好。靠着朱砂的变...
    笨笨的自己阅读 1,483评论 3赞 1

友情链接更多精彩内容