Starting Vocational Training From 1-May-2024 Get Detail


 Write a program in C to count the total number of words in a string.

Test Data :
Input the string : This is sensible academy

Expected Output :

Total number of words in the string is : 4 

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define str_size 100 //Declare the maximum size of the string

void main()
{
    char str[str_size];
    int i, wrd;
    
       printf(" Count the total number of words in a string : ");
       printf("------------------------------------------------------ ");     
       printf("Input the string : ");
       fgets(str, sizeof str, stdin);    
    
    i = 0;
    wrd = 1;

    /* loop till end of string */
    while(str[i]!=)
    {
        /* check whether the current character is white space or new line or tab character*/
        if(str[i]== || str[i]== || str[i]== )
        {
            wrd++;
        }

        i++;
    }

    printf("Total number of words in the string is : %d ", wrd-1);
}