word occurrence in java 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: Write a c++ program that reads a sentence (including spaces) and a word, then print out the number of occurrences of the word in the sentence

Write a c++ program that reads a sentence (including spaces) and a word, then print out the number of occurrences of the word in the sentence

Tags:

Java Example