繁体   English   中英

当尝试根据给定查询查找给定字符串中的子字符串计数时,有人能告诉我我在 Java 代码中做错了什么吗?

[英]Can someone tell me what am I doing wrong here in my Java code when trying to find count of substrings in given string according to given queries?

数组 findStr 中有查询,并且对于每个查询,我都给出了一个目标后缀。 我必须确定数组 strr 中将后缀作为目标后缀的字符串的数量。 查询以字符串数组 findStr 的形式给出。

例子

假设

strr = [“asdfc”、“asfc”、“vdsfc”、“trgfds”、“egregds”、“tertdfc”、“rtyergds”]

findStr = ["dfc", "fc", "ds"]

方法:

在第一个查询中,所需的后缀是“dfc”。 有这个后缀的字符串是 [asdfc, tertdfc]。 因此,计数为 2。

在第二个查询中,所需的后缀是“fc”。 有这个后缀的字符串是 [asdfc, asfc, vdsfc, tertdfc]。 因此,计数为 4。

在第三个查询中,所需的后缀是“ds”。 有这个后缀的字符串是 [trgfds, egregds, rtyergds]。 因此,计数为 3。

因此输出为 [2,4,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;
    }
}
  • 您应该将count变量设置为第一个循环的本地变量,以便每个后缀的计数从 0 开始。

  • 使用String#endsWith检查字符串是否以特定后缀结尾,并在每次为真时将计数加 1。

for (int i = 0; i < findStr.length; i++) {
    int count = 0;
    for(String str: strr)
        if(str.endsWith(findStr[i])) ++count;
    result[i] = count;
}
for(int l: result)
    System.out.println(l);

您需要在每次迭代开始时将count重置为 0。
否则,它也会计算先前子字符串的出现次数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM