Count words in a given 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 ; Given String str ; Print the result
def countWords ( Str ) : NEW_LINE INDENT if ( Str == None or len ( Str ) == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT wordCount = 0 NEW_LINE isWord = False NEW_LINE endOfLine = len ( Str ) - 1 NEW_LINE ch = list ( Str ) NEW_LINE for i in range ( len ( ch ) ) : NEW_LINE INDENT if ( ch [ i ] . isalpha ( ) and i != endOfLine ) : NEW_LINE INDENT isWord = True NEW_LINE DEDENT elif ( not ch [ i ] . isalpha ( ) and isWord ) : NEW_LINE INDENT wordCount += 1 NEW_LINE isWord = False NEW_LINE DEDENT elif ( ch [ i ] . isalpha ( ) and i == endOfLine ) : NEW_LINE INDENT wordCount += 1 NEW_LINE DEDENT DEDENT return wordCount NEW_LINE DEDENT Str =   " One two three NEW_LINE INDENT four five   " NEW_LINE DEDENT print ( " No ▁ of ▁ words ▁ : " , countWords ( Str ) ) NEW_LINE