how to count the number of occurrences of a word in a string in java code example

Example 1: count the number of words in a string java

public static void main(String[] args)
    { 
        //return the number of words in a string 
        
       String example = "This is a good exercise"; 
       
       int length = example.split(" ").length;
       
       System.out.println("The string is " + length + " words long.");
        
        
    }

Example 2: 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');
    }


}

Tags:

Java Example