Copyright © Programs ++
Design by Dzignine
Thursday, 1 March 2012

Counting number of words in a string

This program is used to find the number of words in a string. Now, to do this is actually very simple.
Simply count the number of spaces between words. To do this, simply traverse the string using a loop and
increment a counter variable whenever a space character occurs. Simple :) .!! Do not forget to initialize the
counter variable !!!
Here is the source code : 

// Program to count the number of words in a string
#include <iostream>

int main()
{
     char string[50];
     int counter = 1;
     // prompts the user to enter a string
     std::cout<<" Enter the string ( max 50chars ) : ";
     std::cin.getline(string,sizeof(string));

     for (int i=0; string[i]!= '\0'; i++ )
     {
          if ( string[i] == ' ' )
               counter++;
     }
     std::cout<<"\n Number of Words are : "<<counter;
     return 0;

} // end of main
------ OUTPUT ------








Please do comment if you don't understand any part or want to know more or just want to say thanks. I love programming and love to teach my friends. Your suggestions and appreciation will make this blog much better.  
------ Related Posts ------

2 comments:

  1. what if the string begins with white spaces ???

    ReplyDelete
  2. dont we need any other header files ????

    ReplyDelete

Comment Here....