Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Program to count no of words from given input string.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 139
    Comment on it
    // 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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: