To count the number of words in a given string

Thursday, 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(“nnt ENTER A STRING…: “);
gets(str);
while(str[len]!=’′)
len++;
len–;
for(i=0;i<=len;i++)
{
if ( ( str[i] == ‘ ‘ && str[i+1] != ‘ ‘ ) || i == len )
words++;
}
printf(“nt NUMBER OF WORDS IN THE ABOVE SENTENCE IS…: %d”, words);
getch();
}
Download exe and source code here.

Avatar Image

Author Name :
Ranjith

Total : 6 Comments


6 Responses to “To count the number of words in a given string”

  1. om prakash says:

    Thax dear your code is totally correct

  2. Priya says:

    Your code gives 20 errors!

  3. Eswar says:

    Can you publish the code in java..?

  4. v jain says:

    pls. give output also.

  5. deepak says:

    ur code is wrong…………

    wrong

    not wor for

    dee dee dee

    means if u give spaces many times ur string it does not work.

  6. Sneha S says:

    Dabba program dude….

    Even a small school kind can do this…

    Try something NEW NEW NEW . . . .

Leave a Reply

Question and Answer
C/C++ Unix & Linux Wordpress
Source codes
C C++ Java

Free email signup