C Program to Find Total Words in a String

Introduction

In this post, I am going to write a c program to find total words in a string. We will simply read a string from the console and display total number of words in that string.

Also Read: Program To Reverse a String in C using Pointer

As we know that string is nothing but a collection of characters i.e. character array. So the question is how we are going to find total number of characters in a string.

Suppose, we have a string “Hello, this is c programming blog.” Now, we have 6 words in this string. Words are separated by blank spaces. So, we just need to check the white space or blank space. If we get it then we will increment the value of the counter variable.

Just see the following expected output.

Expected Output

c program to find total words in a string

As you can see the above exptected output, I am asking user to enter a string. When he enters the string, then he is getting the message that total number of words are 6.

Here, I am just counting the total number of blank spaces. Here, total blank spaces are 5. After the last word, there is next line character. So, I make the initial value of the variable count is 1.

I hope you got the logic of this program.

Now, let us see the actual program.

C Program to Find Total Words in a String

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char str[100];
    int i=0;
    int count = 1;
    printf("Enter a string\n");
    gets(str);
    while(str[i]!='\0')
    {
        if((str[i]==32))
        {
            count++;
        }
        i++;
    }
   printf("Total number of words in %s is %d",str,count);
    return 0;
}

From the above program, we are checking each and every character of a string with blank space. Here, I have taken the ASCII value of blank space i.e. 32.

I hope you have understood this program. If you have any difficulty, then please feel free to contact me. Thank you.

Some Important C Programs

  1. Program in C to Find Longest Line in a File
  2. Palindrome in C using Pointers
  3. Insert and Delete element in Array in C using switch case
  4. C Program to Add Alternate Elements of a 2D Array
  5. Arrays in C for Complete Beginners
  6. C Program to Find Area of a Circle using Preprocessor
  7. Program in C to Remove White Spaces and Comments from a File
  8. C Program to Print Numbers Except Multiples of n
  9. Reverse a Number using getchar and putchar function in c
  10. The while loop in C Programming

Leave a Comment