有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java计算字符串中的字符串数

我试图计算文本(字符串)中出现的符号(字符串)的数量。我在这里看到了一些其他的解决方案,但它们更先进或使用库。我的想法是在符号每次出现时减少字符串。我使用.indexOf(symbol,1)从索引1中搜索符号,因为如果它在0处搜索,它就会停止。然而,大多数情况下,代码都会超量计算一次

String text = readLine("Enter text");
String symbol = readLine("Enter symbol");

int count = 0;
while (true) {
    if (!text.contains(symbol)) {
        break;
    }
    count++;
    if ((text.indexOf(symbol, 1)) == -1) {
        break;
    }
    text = text.substring(text.indexOf(symbol, 1));
    System.out.println(text);
    System.out.println(count);
}

System.out.println("Symbol " + symbol + " appears in text " + count + " times.");

请帮我找出逻辑上的缺陷,并告诉我这种方法是好是坏


共 (2) 个答案

  1. # 1 楼答案

    使用substring的另一种方法是跟踪字符串所在的上一个索引,并使用^{}

    int count = 0;
    for(int idx = -1; (idx = text.indexOf(symbol, idx + 1)) != -1; count++);
    System.out.println("Symbol " + symbol + " appears in text " + count + " times.");
    
  2. # 2 楼答案

    由于tibetiroka已经发现了您代码中的缺陷,我将只讨论您问题的第二部分:

    also tell me if this approach is good or bad.

    它可以工作,但它非常复杂,而且在运行时效率不高。原因是substring()将所有剩余字符复制到一个新字符串中。例如,假设文本中包含1000次符号,而没有其他内容。然后,在找到第一个符号后,您的代码将复制剩余的999个符号,在找到第二个符号后复制998个符号,依此类推,总共大约有50万个符号副本,尽管文本中只有1000个符号

    因此,最好避免substring(),而是使用第二个参数indexOf()来继续查看找到的最后一个符号:

    int count = 0;
    int index = 0;
    while (true) {
        index = text.indexOf(symbol, index); // find next occurrence of symbol
        if (index == -1) {
          return count;
        }
        count++;
        index++;
    }
    

    我还取消了contains()的使用,因为indexOf()已经告诉我们是否还有其他情况发生

    最后一件事:您没有指定是否应该计算重叠符号。例如,如果我们在文本“ababa”中查找“aba”,这是一次还是两次?如果事件不应该重叠,我们可以通过在找到符号时说index += symbol.length来实现这一点