C++ Program to Count Number of Words in a String


This is a C++ Program to Find the Number of Words in a Given Sentence.

Problem Description

The program takes a string and counts the number of words in it.

Problem Solution

1. The program takes a string.
2. Using a for loop, the number of spaces in the string are counted.
3. The total number of words will be number of spaces plus 1.
4. The result is printed.
5. Exit.

C++ Program/Source code

Here is the source code of C++ Program to Find the Number of Words in a Given Sentence. The program output is shown below.

  1. #include<iostream>
  2. #include<string.h>
  3. using namespace std;
  4. int main ()
  5. {
  6.     char str[50];
  7.     int count = 0, i; 
  8.     cout << "Enter a string : ";
  9.     gets(str);
  10.     for (i = 0; str[i] != '\0';i++)
  11.     {
  12.         if (str[i] == ' ')
  13.             count++;    
  14.     }
  15.     cout << "Number of words in the string are: " << count + 1;
  16.     return 0;
  17. }
Program Explanation

1. The user is asked to enter a string and stored in the array ‘str’. A variable ‘count’ is initialized as 0.
2. Using for loop, for every space(‘ ‘) in the string, count is incremented.
3. The loop continues till the end of the string.
4. Increment the value of count by 1 and then the result is printed, which is the total number of words.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
Runtime Test Cases
Case 1 :
Enter a string : Mosaic
Number of words in the string are : 1
Case 2 :
Enter a string : 1 2 3 4 5
Number of words in the string are : 5
Case 3 :
Enter string 1 : The sun shines brightly.
Number of words in the string are: 4

Sanfoundry Global Education & Learning Series – C++ Programs.

To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.

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 & technical discussions at Telegram SanfoundryClasses.