C Program to Count Number of Words in a String

This is a C Program to Count the Number of Words in a given text or Sentence.

Problem Description

This program takes a string as input and count the number of words in the input string.

Problem Solution

1. Take a string as input.
2. Using for loop search for a empty space in between the words in the string.
3. Consecutively increment a variable. This variable gives the count of number of words.

Program/Source Code

Here is source code of the C Program to Count the Number of Words in a given text Or Sentence. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C Program to Count Number of Words in a given Text Or Sentence
  3.  */
  4. #include <stdio.h>
  5. #include <string.h>
  6.  
  7. void main()
  8. {
  9.     char s[200];
  10.     int count = 0, i;
  11.  
  12.     printf("Enter the string:\n");
  13.     scanf("%[^\n]s", s);
  14.     for (i = 0;s[i] != '\0';i++)
  15.     {
  16.         if (s[i] == ' ' && s[i+1] != ' ')
  17.             count++;    
  18.     }
  19.     printf("Number of words in given string are: %d\n", count + 1);
  20. }
Program Explanation

1. Take a string as input and store it in the array s[].
2. Using for loop search for a space ‘ ‘ in the string and consecutively increment a variable count.
3. Do step-2 until the end of the string.
4. Increment the variable count by 1 and then print the variable count as output.

advertisement
advertisement
Runtime Test Cases
Enter the string:
welcome to sanfoundry's c-programming class!
Number of words in given string are: 5
 
Enter the string:
Best Books in C Programming
Number of words in given string are: 6

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

Note: Join free Sanfoundry classes at Telegram or Youtube
If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.