find number of occurrences of a substring in a string java code example

Example 1: number of occurence string in java

public class StringNumberOfOccurenceLetter {

    private static int countOccurences(String word, char character){

        int count = 0;
        for (int i = 0; i < word.length() ; i++) {
            if (word.charAt(i)==character){
                count++;
            }
        }
        return count;

    }
         public static void main(String[] args) {


        int count = countOccurences("dddssad", 'a');
    }


}

Example 2: find number of occurrences of a substring in a string java

public static int count(String str, String target) {
    return (str.length() - str.replace(target, "").length()) / target.length();
}

Tags:

Misc Example