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
- Run a
forloop, starting from 0 to the size of the string - 1, i.e., fromi=0toi==str.size(). - Check if
str[i]is a space character. If it is, a new word will start, so increment word count by one. - The
forloop will run to the end of the string, and the number of spaces will be counted. - Increment the number of spaces by 1 to get the number of words.
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 stringstring sentence = "Mary had a little lamb";// initialising no of words to 0int words = 0;// store length of string in lenOfSentenceint lenOfSentence = sentence.size();// run for loop from i = 0 to i < lenOfSentence// to iterate through each character of the stringfor(int i = 0; i < lenOfSentence; i++){// check if current character is a spaceif(sentence[i] == ' '){// if it is a space, increment word countwords++;}}// at the end of the for loop, no. of spaces have been// counted. Increment word count one more time to get// no. of wordswords = 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 stringstring sentence = "Mary had a little lamb";// initialising no of words to 0int words = 0;// store length of string in lenOfSentenceint lenOfSentence = sentence.size();// run while loop from i = 0 to i < lenOfSentence// to iterate through each character of the stringint i = 0;while (i < lenOfSentence){// check if current character is a spaceif(sentence[i] == ' '){// if it is a space, increment word countwords++;}i++;}// at the end of the while loop, no. of spaces have been// counted. Increment word count one more time to get// no. of wordswords = 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.