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