Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


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

Sarah Tanveer

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

Explanation of algorithm

This simple algorithm uses a for 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
#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

  // 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;




View all Courses

Keep Exploring