text: Count words in a given string | Java program to count total number of words in the string ; Function to count total number of words in the string ; Check if the string is null or empty then return zero ; Converting the given string into a character array ; Check if the character is a letter and index of character array doesn 't  equal to end of line that means, it is  a word and set isWord by true ; Check if the character is not a letter that means there is a space , then we increment the wordCount by one and set the isWord by false ; Check for the last word of the sentence and increment the wordCount by one ; Return the total number of words in the string ; Driver Code ; Given String str ; Print the result
code: class GFG { public static int countWords ( String str ) { if ( str == null || str . isEmpty ( ) ) return 0 ; int wordCount = 0 ; boolean isWord = false ; int endOfLine = str . length ( ) - 1 ; char [ ] ch = str . toCharArray ( ) ; for ( int i = 0 ; i < ch . length ; i ++ ) { if ( Character . isLetter ( ch [ i ] ) && i != endOfLine ) isWord = true ; else if ( ! Character . isLetter ( ch [ i ] ) && isWord ) { wordCount ++ ; isWord = false ; } else if ( Character . isLetter ( ch [ i ] ) && i == endOfLine ) wordCount ++ ; } return wordCount ; } public static void main ( String args [ ] ) { String str = "One two	three four five "; System . out . println ( " No ▁ of ▁ words ▁ : ▁ " + countWords ( str ) ) ; } }