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

简介: String字符串中获取所有匹配结果的索引值例如现在我们有这样一段代码public interface ActErrorHisMapper { public List getPage(Map params); public L...

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

相关文章
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
326 100
|
3月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
440 99
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
3月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
4月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
287 92
|
5月前
|
自然语言处理 Java Apache
在Java中将String字符串转换为算术表达式并计算
具体的实现逻辑需要填写在 `Tokenizer`和 `ExpressionParser`类中,这里只提供了大概的框架。在实际实现时 `Tokenizer`应该提供分词逻辑,把输入的字符串转换成Token序列。而 `ExpressionParser`应当通过递归下降的方式依次解析
339 14
|
9月前
|
数据处理
鸿蒙开发:ArkTs字符串string
字符串类型是开发中非常重要的一个数据类型,除了上述的方法概述之外,还有String对象,正则等其他的用处,我们放到以后得篇章中讲述。
519 19
|
安全 Java API
【Java字符串操作秘籍】StringBuffer与StringBuilder的终极对决!
【8月更文挑战第25天】在Java中处理字符串时,经常需要修改字符串,但由于`String`对象的不可变性,频繁修改会导致内存浪费和性能下降。为此,Java提供了`StringBuffer`和`StringBuilder`两个类来操作可变字符串序列。`StringBuffer`是线程安全的,适用于多线程环境,但性能略低;`StringBuilder`非线程安全,但在单线程环境中性能更优。两者基本用法相似,通过`append`等方法构建和修改字符串。
251 1