// C++ program to count no of words from given input string.
#include <stdio.h>
#define separator 0
#define word 1
unsigned countWords(char *str) // returns number of words in str
{
int state = separator;
unsigned wc = 0; // word count
while (*str) // Scan all characters one by one
{
// If next character is a separator, set the
// state as separator
if (*str == ' ' || *str == '\n' || *str == '\t')
state = separator;
// If next character is not a word separator and
// state is separator, then set the state as word and
// increment word count
else if (state == separator)
{
state = word;
++wc;
}
// Move to next character
++str;
}
return wc;
}
int main(void)
{
char str[] = "One two three\n four\nfive ";
printf("No of words: %u\n", countWords(str));
return 0;
}
Output:
No of words: 5
Explanation:
In above program two macros word and separator is defined which are used to maintain state i.e the state separator indicate there is a separator e.g '\n','\t' etc in the input string while the state word indicate a word in the input string. In countWords function,while loop runs till null is found and within the function if condition checks whether str is space or new line or tab if true state is set to separator else increment word count (wc) when previous state is separator and next character is a word character.
0 Comment(s)