string count word in a string code example

Example 1: check how many of a word is in a string

function countOccurences(str,word)  
{ 
    // split the string by spaces in a 
    String a[] = str.split(","); 
  
    // search for pattern in a 
    int count = 0; 
    for (int i = 0; i < a.length; i++)  
    { 
    // if match found increase count 
    if (word.equals(a[i])) 
        count++; 
    } 
  
    return count; 
}

Example 2: how to count words in string

String str = "I am happy and why not
  and why are you not happy and you should be";
        String [] arr = str.split(" ");
        Map map = new HashMap<>();

        for (int i=0 ; i < arr.length ; i++){
                if (!map.containsKey(arr[i])){
                    map.put(arr[i],1);
                } else{
                    map.put(arr[i],map.get(arr[i])+1);
                }
        }
        for(Map.Entry each : map.entrySet()){

  System.out.println(each.getKey()+" occures " + each.getValue() + " times");
        }

Tags: