Given a string, count number of words in it. The words are separated by following characters: space (‘ ‘) or new line (‘\n’) or tab (‘\t’) or a combination of these.
There can be many solutions to this problem. Following is a simple and interesting solution.
The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator is seen. State IN indicates that a word character is seen. We increment word count when previous state is OUT and next character is a word character.
Read full article from Count words in a given string | GeeksforGeeks
There can be many solutions to this problem. Following is a simple and interesting solution.
The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator is seen. State IN indicates that a word character is seen. We increment word count when previous state is OUT and next character is a word character.
unsigned countWords(char *str){ int state = OUT; unsigned wc = 0; // word count // Scan all characters one by one while (*str) { // If next character is a separator, set the state as OUT if (*str == ' ' || *str == '\n' || *str == '\t') state = OUT; // If next character is not a word separator and state is OUT, // then set the state as IN and increment word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++str; } return wc;}