You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现字符串后缀计数功能输出结果错误问题排查

Java字符串后缀统计结果错误问题定位

问题复现

需求为给定字符串数组strr与查询数组findStr,统计strr中以每个查询项为后缀的元素总数。

  • 测试输入strr = ["asdfc", "asfc", "vdsfc", "trgfds", "egregds", "tertdfc", "rtyergds"]
  • 测试输入findStr = ["dfc", "fc", "ds"]
  • 预期输出:[2,4,3]
    1. 后缀"dfc"匹配["asdfc", "tertdfc"],计数2
    2. 后缀"fc"匹配["asdfc", "asfc", "vdsfc", "tertdfc"],计数4
    3. 后缀"ds"匹配["trgfds", "egregds", "rtyergds"],计数3
  • 实际错误输出:[2,6,10]

原问题代码如下:

class FindCount {
    public static void main(String[] args) {
        String[] strr = new String[]{"asdfc", "asfc", "vdsfc", "trgfds", "egregds", "tertdfc", "rtyergds"};

        String[] findStr = new String[]{"dfc", "fc", "ds"};
        int count = 0;
        int result[] = new int[findStr.length];

        for (int i = 0; i < findStr.length; i++) {
            for (int j = 0; j < strr.length; j++) {
                count += findCount(strr[j], findStr[i]);
            }
            result[i] = count;
        }
        for(int l: result)
        System.out.println(l);
    }

    static int findCount(String str, String findStr) {
        int lastIndex = 0;
        int count = 0;

        while (lastIndex != -1) {

            lastIndex = str.indexOf(findStr, lastIndex);
            if (lastIndex != -1) {
                count++;
                lastIndex += findStr.length();
            }
        }
        return count;
    }
}

逻辑错误点

代码一共存在两处核心逻辑错误:

  1. 计数变量未按查询项重置
    外层循环遍历每个查询后缀时,没有把count清零。第一个查询统计完得到2之后,第二个查询的计数是在2的基础上累加,第三个查询又在前两个的结果上累加,最终结果会累计之前所有查询的计数,数值越算越大。
  2. 匹配逻辑不符合后缀判断要求
    自定义的findCount方法是统计子串在字符串中所有出现位置的次数,根本不是判断字符串是否以目标子串结尾。比如查询"fc"时,只要字符串里任意位置出现"fc"都会被计数,哪怕"fc"不在字符串末尾;而且同一个字符串里如果多次出现目标子串还会重复计数,完全不符合后缀统计的要求。
    Java本身提供了String.endsWith()方法专门用来判断字符串是否以指定后缀结尾,不需要自己写子串遍历逻辑。

修复后代码

class FindCount {
    public static void main(String[] args) {
        String[] strr = new String[]{"asdfc", "asfc", "vdsfc", "trgfds", "egregds", "tertdfc", "rtyergds"};
        String[] findStr = new String[]{"dfc", "fc", "ds"};
        int result[] = new int[findStr.length];

        for (int i = 0; i < findStr.length; i++) {
            // 每个查询项开始统计前先把计数清零
            int count = 0;
            String targetSuffix = findStr[i];
            for (int j = 0; j < strr.length; j++) {
                // 直接用endsWith判断是否为后缀,符合条件才计数+1
                if (strr[j].endsWith(targetSuffix)) {
                    count++;
                }
            }
            result[i] = count;
        }
        for(int l: result) {
            System.out.println(l);
        }
    }
}

运行修复后的代码即可得到预期输出[2,4,3]。


内容的提问来源于stack exchange,提问作者gulzar1337

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 04:45:38