Question: Find the number of words in a given string?
Input: This is a sample statement and I need to find the number of words.
Output: 14
According to the problem, we are given a string and it contain words separated by spaces, next lines or tab spaces. So, the basic idea for the problem would be to traverse the string and increment a counter whenever we see the end of a word.
/* Program to count no of words from given input string. */ #include <stdio.h> // returns number of words in str int countWords(char *str) { // We use a flag variable, flag = 1 means word has not been found // flag = 0 means we are traversing a word int flag = 1; int wordCount = 0; // word count // Scan all characters one by one while (*str) { // If next character is a separator, set the flag if (*str == ' ' || *str == '\n' || *str == '\t') flag = 1; else if (flag == 1) { // If next character is not a word separator and flag is 1 // then set the flag as 0 and increment word count flag = 0; ++wordCount; } // Move to next character ++str; } return wordCount; } // Driver program to test above function int main(void) { char str[] = "This is a sample statement and I need to find the number of words."; printf("No of words: %d\n", countWords(str)); return 0; }