Count words in a given string | C # 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
using System ; public class GFG { static int countWords ( String str ) { if ( str == null ) { return 0 ; } int wordCount = 0 ; bool isWord = false ; int endOfLine = str . Length - 1 ; char [ ] ch = str . ToCharArray ( ) ; for ( int i = 0 ; i < ch . Length ; i ++ ) { if ( Char . IsLetter ( ch [ i ] ) && i != endOfLine ) { isWord = true ; } else if ( ! Char . IsLetter ( ch [ i ] ) && isWord ) { wordCount ++ ; isWord = false ; } else if ( Char . IsLetter ( ch [ i ] ) && i == endOfLine ) { wordCount ++ ; } } return wordCount ; } static public void Main ( ) { string str = " One ▁ two TABSYMBOL three STRNEWLINE ▁ four TABSYMBOL five ▁ " ; Console . WriteLine ( " No ▁ of ▁ words ▁ : ▁ " + countWords ( str ) ) ; } }