Electrofriends

To count the number of words in a given string

by Ranjith | December 4th, 2008.

This is the program to count number of words in the entered sentence.

Logic: The logic behind this program is checking if the character in the sentence is a ‘blank’ and with the conditions that the next is not a blank character, or current character position is not equal to length of the sentence. If so, variable ‘words’ is incremented by one as one new word found.

#include<stdio.h>
#include<conio.h>
void main()
{
char str[50];
int words = 0, len = 0, i;
clrscr();
printf(“\n\n\t ENTER A STRING…: “);
gets(str);
while(str[len]!=’\0′)
len++;
len–;
for(i=0;i<=len;i++)
{
if ( ( str[i] == ‘ ‘ && str[i+1] != ‘ ‘ ) || i == len )
words++;
}
printf(“\n\t NUMBER OF WORDS IN THE ABOVE SENTENCE IS…: %d”, words);
getch();
}
Download exe and source code here.


Share and Enjoy:
  • Digg
  • Technorati
  • StumbleUpon
  • Twitter
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Reddit
  • Mixx
  • Yahoo! Buzz
  • LinkedIn
  • NewsVine
  • RSS
  • email
Similar Posts:

One Response to “To count the number of words in a given string”

  1. 1
    om prakash Says:

    Thax dear your code is totally correct

Leave a Reply

Share and enjoy

    • Digg
    • Facebook
    • Technorati
    • StumbleUpon
    • Twitter
    • Reddit
    • del.icio.us
    • Yahoo! Buzz
Copyright©2009 www.electrofriends.com All Rights Reserved. Powered by Dhyeya