5

我需要输入两个字符串,第一个是任何单词,第二个字符串是前一个字符串的一部分,我需要输出第二个字符串出现的次数。例如:字符串 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当我使用此代码时它会输出。

4

4 回答 4

11

有趣的解决方案:

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

基本上我们在这里所做的是main从删除所有 in 实例所产生的字符串长度sub中减去长度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();
}
于 2012-09-07T19:32:06.690 回答
3

你也可以试试:

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);
}
于 2012-09-07T19:35:53.003 回答
1

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

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;
}
于 2016-11-27T19:44:25.673 回答
0

另外一个选项:

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();
}

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

于 2014-02-24T15:15:50.443 回答