C++ Program to Count Number of Words in a String
Posted by Superadmin on August 10 2022 13:04:34

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.

 
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