Java - Write code to Return the number of times a particular String occurs in another String.

Requirements

Write code to Return the number of times a particular String occurs in another String.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String content = "book2s.com";
        String occurs = "o";
        System.out.println(countOccurances(content, occurs));
    }/*from ww w . j av a2s.  co m*/

    /**
     * Returns the number of times a particular String occurs in another String.
     * e.g. count the number of single quotes.
     */
    public static int countOccurances(String content, String occurs) {
        return countOccurances(content, occurs, 0, 0);
    }

    private static int countOccurances(String content, String occurs,
            int pos, int countSoFar) {
        int equalsPos = content.indexOf(occurs, pos);
        if (equalsPos > -1) {
            countSoFar = countSoFar + 1;
            pos = equalsPos + occurs.length();
            // dp("countSoFar="+countSoFar+" pos="+pos);
            return countOccurances(content, occurs, pos, countSoFar);
        } else {
            return countSoFar;
        }
    }
}

Related Exercise