Count total number of words in a sentence
C program to count the total number of words in a sentence.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
char str[MAX], prev_char;
int i, word;
printf("Enter the string\t:");
gets(str);
word = 0;
i = 0;
prev_char = '\0';
while(1)
{
if(str[i] == ' ' || str[i] == '\t' || str[i] == '\0')
{
if(prev_char!=' ' && prev_char!='\t' && prev_char!='\0')
{
word++;
}
}
prev_char = str[i];
if(str[i] == '\0')
break;
else
i++;
}
printf("\nNumber of words\t:%d",word);
getch();
}
Output
Enter the string :welcome to coursecrux.com. happy coding!!
Number of words :5