text: Count occurrences of a word in string | Java program to count the number of occurrence of a word in the given string ; split the string by spaces in a ; search for pattern in a ; if match found increase count ; Driver code
code: import java . io . * ; class GFG { static int countOccurrences ( String str , String word ) { String a [ ] = str . split ( " ▁ " ) ; int count = 0 ; for ( int i = 0 ; i < a . length ; i ++ ) { if ( word . equals ( a [ i ] ) ) count ++ ; } return count ; } public static void main ( String args [ ] ) { String str = " GeeksforGeeks ▁ A ▁ computer ▁ science ▁ portal ▁ for ▁ geeks ▁ " ; String word = " portal " ; System . out . println ( countOccurrences ( str , word ) ) ; } }