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 :
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 ------
Converting a string to uppercase : http://programsplusplus.blogspot.in/2012/02/converting-array-of-string-to-uppercase.html
what if the string begins with white spaces ???
ReplyDeletedont we need any other header files ????
ReplyDelete