String字符串中获取所有匹配结果的索引值
例如现在我们有这样一段代码
public interface ActErrorHisMapper { public ListgetPage(Map params); public List getList(Map params); public int getCount(Map params);}复制代码
我们要查找所有的public
关键字出现的索引,那么可以这么写
public static ListfindAllIndex(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 ListgetPage(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); } }复制代码
输出结果如下:
042106170复制代码