How to find the number of words in a sentence in C++

This Answer describes the method to count the number of words in a sentence in C++.

Explanation of algorithm

This simple algorithm uses a for or while loop to iterate through a string and counts the number of spaces in the sentence.

In C++, a string acts like an array of characters, and its elements can be accessed through indexing, like in an array. The number of words is equal to the number of spaces + 1.

Dry run

  1. Run a for loop, starting from 0 to the size of the string - 1, i.e., from i=0 to i==str.size().
  2. Check if str[i] is a space character. If it is, a new word will start, so increment word count by one.
  3. The for loop will run to the end of the string, and the number of spaces will be counted.
  4. Increment the number of spaces by 1 to get the number of words.
1 of 10

Using the for loop

Let's implement the logic for finding the number of words in a sentence using the for loop.

#include <iostream>
using namespace std;
int main() {
// declaring string
string sentence = "Mary had a little lamb";
// initialising no of words to 0
int words = 0;
// store length of string in lenOfSentence
int lenOfSentence = sentence.size();
// run for loop from i = 0 to i < lenOfSentence
// to iterate through each character of the string
for(int i = 0; i < lenOfSentence; i++)
{
// check if current character is a space
if(sentence[i] == ' ')
{
// if it is a space, increment word count
words++;
}
}
// at the end of the for loop, no. of spaces have been
// counted. Increment word count one more time to get
// no. of words
words = words + 1;
cout << "No. of words = " << words << endl;
}

Using the while loop

Let's implement the logic for finding the number of words in a sentence using the while loop.

#include <iostream>
using namespace std;
int main() {
// declaring string
string sentence = "Mary had a little lamb";
// initialising no of words to 0
int words = 0;
// store length of string in lenOfSentence
int lenOfSentence = sentence.size();
// run while loop from i = 0 to i < lenOfSentence
// to iterate through each character of the string
int i = 0;
while (i < lenOfSentence)
{
// check if current character is a space
if(sentence[i] == ' ')
{
// if it is a space, increment word count
words++;
}
i++;
}
// at the end of the while loop, no. of spaces have been
// counted. Increment word count one more time to get
// no. of words
words = words + 1;
cout << "No. of words = " << words << endl;
}

The while loop continues until all characters in the sentence have been processed. Each space encountered within the loop increments the words count. Upon completion of the loop, the variable words holds the total number of words in the sentence.

Free Resources