【问题标题】:Getting the number of occurrences of one string in another string获取一个字符串在另一个字符串中出现的次数
【发布时间】:2012-09-07 19:29:43
【问题描述】:

我需要输入两个字符串,第一个是任何单词,第二个字符串是前一个字符串的一部分,我需要输出第二个字符串出现的次数。例如:字符串 1 = CATSATONTHEMAT 字符串 2 = AT。输出将为 3,因为 AT 在 CATSATONTHEMAT 中出现了 3 次。这是我的代码:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String word8 = sc.next();
    String word9 = sc.next();
    int occurences = word8.indexOf(word9);
    System.out.println(occurences);
}

当我使用此代码时,它会输出1

【问题讨论】:

  • indexOf 不返回计数,它返回第一次出现的位置。 Javadocs
  • 精确复制到以下字符串:stackoverflow.com/questions/12309109/…
  • @Brian 这就是他寻求帮助的原因。无论如何,正则表达式来拯救?
  • 为什么没有人想写一个循环??

标签: java string indexof


【解决方案1】:

有趣的解决方案:

public static int countOccurrences(String main, String sub) {
    return (main.length() - main.replace(sub, "").length()) / sub.length();
}

基本上,我们在这里所做的是从删除mainsub 的所有实例所产生的字符串长度中减去main 的长度 - 然后我们将这个数字除以sub 的长度来确定有多少次出现的sub 被删除,给我们答案。

所以最后你会得到这样的东西:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String word8 = sc.next();
    String word9 = sc.next();
    int occurrences = countOccurrences(word8, word9);
    System.out.println(occurrences);

    sc.close();
}

【讨论】:

  • 聪明 :) 但是.replace 会更好,因为它不像.replaceAll 那样使用正则表达式,而且它的语义与您使用的相同。
  • 感谢这是一个有趣的方法
【解决方案2】:

你也可以试试:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

    String word8 = sc.nextLine();
    String word9 = sc.nextLine();
    int index = word8.indexOf(word9);
    sc.close();
    int occurrences = 0;
    while (index != -1) {
        occurrences++;
        word8 = word8.substring(index + 1);
        index = word8.indexOf(word9);
    }
    System.out.println("No of " + word9 + " in the input is : " + occurrences);
}

【讨论】:

  • 别忘了关闭您的扫描仪。
【解决方案3】:

为什么没有人发布最明显和最快速的解决方案?

int occurrences(String str, String substr) {
    int occurrences = 0;
    int index = str.indexOf(substr);
    while (index != -1) {
        occurrences++;
        index = str.indexOf(substr, index + 1);
    }
    return occurrences;
}

【讨论】:

    【解决方案4】:

    另一种选择:

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
    
        String word8 = sc.next();
        String word9 = sc.next();
        int occurences = word8.split(word9).length;
        if (word8.startsWith(word9)) occurences++;
        if (word8.endsWith(word9)) occurences++;
        System.out.println(occurences);
    
        sc.close();
    }
    

    startsWithendsWith 是必需的,因为 split() 省略了尾随的空字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-04
      • 1970-01-01
      • 2011-07-13
      • 1970-01-01
      • 2011-07-01
      • 2020-04-28
      • 2014-11-14
      • 1970-01-01
      相关资源
      最近更新 更多