Getting the number of occurrences of one row in another row

I need to enter two lines, the first of which is any word, and the second line is part of the previous line, and I need to print the number of times that has the number of the second line. So for example: String 1 = CATSATONTHEMAT String 2 = AT. The output will be 3, because AT occurs three times in CATSATONTHEMAT. Here is my code:

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

It outputs 1when I use this code.

+5
source share
4 answers

You can also try:

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
source

An interesting solution:

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

, , main , 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();
}
+11

Why doesn’t anyone publish the most obvious and quickest solution?

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;
}
+1
source

Another option:

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

startsWithand endsWithare required because it split()omits the final empty lines.

0
source

All Articles