C Program to Count total Number of Words in a text

Write a c program to take input from the user and count the total number of words in a string

#include<stdio.h>
int main()
{
    char s[50];
    int i,c=0,b=0;
    /* take String input from user */
    printf("enter a string:");
    gets(s);
    for(i=1;s[i]!='\0';i++)
    {
        if(s[i]==' ' || s[i] == '\n' || s[i] == '\t')
        {  /* b count total space*/     
            b++;
            /* c count total previous space */
            if(s[i-1]==s[i])
                c++;
        }
    }
    printf("number of word in a string is %d",b-c+1);
    return 0;
}

output

enter a string: hello  learn    from Studyfame.com
number of word in a string is 4

Explanation of C program to count total words in the text or string

  1. Take a string text from the user and store it in a variable s.
  2. Iterate loop from 1 to end of string i.e '\0'. every string contains a null character at the end i.e '\0'.
  3. inside a loop, count all space (' '), newline '\n', or  tab  '\t' present in string and store it in variable b. count all previous space and store it in variable c
  4. subtract all the previous space i.e c from total space i.e b and add 1. you will get the total word in a string.

For example, Sentence:- 'learn from     studyfame'.

In the above sentence, 1 space between 'learn' and 'from'.

5 space between 'from' and 'studyfame'.

b = 5 + 1 i.e total space = 6.

c = 4 i.e four previous space exist between 'from' and 'studyfame'.

total word = b - c + 1 (6 - 4 + 1 = 3), total word=3.

time complexity: 0(n)