Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the number of occurrences of one string in another string

I need to input a two strings, with the first one being any word and the second string being a part of the previous string and i need to output the number of times string number two occurs. So for instance:String 1 = CATSATONTHEMAT String 2 = AT. Output would 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 1 when I use this code.

like image 250
Eric Avatar asked Sep 07 '12 19:09

Eric


3 Answers

Interesting solution:

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

Basically what we're doing here is subtracting the length of main from the length of the string resulting from deleting all instances of sub in main - we then divide this number by the length of sub to determine how many occurrences of sub were removed, giving us our answer.

So in the end you would have something like this:

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();
}
like image 160
arshajii Avatar answered Sep 23 '22 20:09

arshajii


You could 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);
}
like image 34
David Kroukamp Avatar answered Sep 25 '22 20:09

David Kroukamp


Why no one posts the most obvious and fast 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;
}
like image 43
Desik Avatar answered Sep 23 '22 20:09

Desik