获取另一个字符串中一个字符串的出现次数

Eri*_*ric 5 java string indexof

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

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);
}
Run Code Online (Sandbox Code Playgroud)

1在我使用此代码时输出.

ars*_*jii 11

有趣的解决方案:

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

基本上我们在这里做的是main从删除所有subin的实例中减去字符串长度的长度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();
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*amp 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);
}
Run Code Online (Sandbox Code Playgroud)