text: Count words in a given string | Java 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: public class GFG { static final int OUT = 0 ; static final int IN = 1 ; static int countWords ( String str ) { int state = OUT ; int wc = 0 ; int i = 0 ; while ( i < str . length ( ) ) { if ( str . charAt ( i ) == ' ▁ ' || str . charAt ( i ) == 'NEW_LINE' || str . charAt ( i ) == ' TABSYMBOL ' ) state = OUT ; else if ( state == OUT ) { state = IN ; ++ wc ; } ++ i ; } return wc ; } public static void main ( String args [ ] ) { String str = "One two	three four five "; System . out . println ( " No ▁ of ▁ words ▁ : ▁ " + countWords ( str ) ) ; } }