text: Count words in a given string | C # program to count no of words from given input string . ; returns number of words in str ; word count ; Scan all characters one by one ; If next character is a separator , set the state as OUT ; If next character is not a word separator and state is OUT , then set the state as IN and increment word count ; Move to next character ; Driver program to test above functions
code: using System ; class GFG { static int OUT = 0 ; static int IN = 1 ; static int countWords ( String str ) { int state = OUT ; int wc = 0 ; int i = 0 ; while ( i < str . Length ) { if ( str [ i ] == ' ▁ ' str [ i ] == ' STRNEWLINE ' str [ i ] == ' TABSYMBOL ' ) state = OUT ; else if ( state == OUT ) { state = IN ; ++ wc ; } ++ i ; } return wc ; } public static void Main ( ) { String str = " One ▁ two TABSYMBOL three STRNEWLINE ▁ four TABSYMBOL five ▁ " ; Console . WriteLine ( " No ▁ of ▁ words ▁ : ▁ " + countWords ( str ) ) ; } }