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

复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值