0
0
CppProgramBeginner · 2 min read

C++ Program to Count Words in a String

You can count words in a string in C++ by using std::istringstream to split the string by spaces and count each extracted word, like this: std::istringstream iss(str); while (iss >> word) count++;.
📋

Examples

InputHello world
Output2
InputCount the number of words in this sentence
Output7
Input
Output0
🧠

How to Think About It

To count words in a string, think of words as groups of characters separated by spaces. We can split the string by spaces and count how many groups we get. Using a stream to read each word one by one makes counting easy and reliable.
📐

Algorithm

1
Get the input string from the user.
2
Create a stream to read the string word by word.
3
Initialize a counter to zero.
4
Extract each word from the stream until no words remain.
5
Increase the counter for each extracted word.
6
Return or print the final count.
💻

Code

cpp
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string str;
    std::getline(std::cin, str);

    std::istringstream iss(str);
    std::string word;
    int count = 0;

    while (iss >> word) {
        count++;
    }

    std::cout << count << std::endl;
    return 0;
}
Output
2
🔍

Dry Run

Let's trace the input "Hello world" through the code

1

Input string

str = "Hello world"

2

Create string stream

iss contains "Hello world"

3

Initialize count

count = 0

4

Extract first word

word = "Hello", count = 1

5

Extract second word

word = "world", count = 2

6

No more words

Loop ends, final count = 2

Extracted WordCount
Hello1
world2
💡

Why This Works

Step 1: Reading the string

We use std::getline to read the entire line including spaces into a string.

Step 2: Using string stream

The std::istringstream lets us treat the string like a stream to extract words separated by spaces easily.

Step 3: Counting words

Each time we extract a word with iss >> word, we increase the count by one until no words remain.

🔄

Alternative Approaches

Manual iteration with character check
cpp
#include <iostream>
#include <string>

int main() {
    std::string str;
    std::getline(std::cin, str);
    int count = 0;
    bool inWord = false;

    for (char c : str) {
        if (isspace(c)) {
            if (inWord) {
                count++;
                inWord = false;
            }
        } else {
            inWord = true;
        }
    }
    if (inWord) count++;

    std::cout << count << std::endl;
    return 0;
}
This method manually checks each character to detect word boundaries, useful if you want more control but is more complex.
Using std::count_if with isspace
cpp
#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string str;
    std::getline(std::cin, str);

    int count = 0;
    bool inWord = false;

    for (char c : str) {
        if (isspace(c)) {
            if (inWord) {
                count++;
                inWord = false;
            }
        } else {
            inWord = true;
        }
    }
    if (inWord) count++;

    std::cout << count << std::endl;
    return 0;
}
This approach is similar to manual iteration but uses standard library functions for clarity.

Complexity: O(n) time, O(n) space

Time Complexity

The program reads each character once to extract words, so it runs in linear time relative to the string length.

Space Complexity

The string stream uses extra space proportional to the input string size, so space complexity is O(n).

Which Approach is Fastest?

Using std::istringstream is simple and efficient for most cases, while manual iteration can be slightly faster but more complex.

ApproachTimeSpaceBest For
std::istringstreamO(n)O(n)Simple and readable word counting
Manual iterationO(n)O(1)Fine control and minimal extra space
std::count_if with isspaceO(n)O(1)Readable manual counting with standard functions
💡
Use std::istringstream to easily split and count words in a string.
⚠️
Beginners often forget to handle empty strings or multiple spaces, which can cause incorrect counts.