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 code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; #define OUT  0 NEW_LINE #define IN  1 NEW_LINE unsigned countWords ( char * str ) { int state = OUT ; unsigned wc = 0 ; while ( * str ) { if ( * str == ' ▁ ' * str == ' ' * str == ' TABSYMBOL ' ) state = OUT ; else if ( state == OUT ) { state = IN ; ++ wc ; } ++ str ; } return wc ; } int main ( void ) { char str [ ] = " One ▁ two TABSYMBOL three STRNEWLINE ▁ four TABSYMBOL five ▁ " ; cout << " No ▁ of ▁ words ▁ : ▁ " << countWords ( str ) ; return 0 ; }