查找指定字符串第n次出现的下标

发布时间:2022-06-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了查找指定字符串第n次出现的下标脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

查找指定字符串第n次出现的下标

    /**
     * 根据findStr在data查找第count次出现的下标
     * @param data 字符串标本
     * @param findStr 要查找的字符串
     * @param count 次数
     * @return
     */
    public static int findStrIndex(String data, String findStr, int count) {
        int indexCount = 0;
        int resultIndex = -1;
        int length = findStr.length();
        char[] findCharArray = findStr.toCharArray();
        char[] dataArray = data.toCharArray();
        for (int i = 0; i < dataArray.length; i++) {
            char dataChar = dataArray[i];
            char findChar = findCharArray[0];
            if(findChar == dataChar) {
                String match = "";
                for (int i1 = i; i1 < i+length; i1++) {
                    match += dataArray[i1];
                }
                if(findStr.equals(match)) {
                    indexCount++;
                    if(count == indexCount) {
                        resultIndex = i;
                        break;
                    }
                }
            }
        }
        return resultIndex;
    }

&nbsp;运行结果:

        String data = "我叫张万森我叫张万森我叫张万森";
        String findStr = "张万森";
        int index = findStrIndex(data, findStr, 3);
        System.out.PRintln(index); // 12

 

脚本宝典总结

以上是脚本宝典为你收集整理的查找指定字符串第n次出现的下标全部内容,希望文章能够帮你解决查找指定字符串第n次出现的下标所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。