C++ Program to Count Words in a String
std::istringstream to split the string by spaces and count each extracted word, like this: std::istringstream iss(str); while (iss >> word) count++;.Examples
How to Think About It
Algorithm
Code
#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; }
Dry Run
Let's trace the input "Hello world" through the code
Input string
str = "Hello world"
Create string stream
iss contains "Hello world"
Initialize count
count = 0
Extract first word
word = "Hello", count = 1
Extract second word
word = "world", count = 2
No more words
Loop ends, final count = 2
| Extracted Word | Count |
|---|---|
| Hello | 1 |
| world | 2 |
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
#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; }
#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; }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| std::istringstream | O(n) | O(n) | Simple and readable word counting |
| Manual iteration | O(n) | O(1) | Fine control and minimal extra space |
| std::count_if with isspace | O(n) | O(1) | Readable manual counting with standard functions |
std::istringstream to easily split and count words in a string.