JuniorCodeCommonNot answered yet
Count words in a sentence
Given a sentence, return the number of words in it. Words are separated by whitespace.
Requirements:
- Handle multiple consecutive spaces and leading/trailing spaces correctly.
- The empty string (and a string of only spaces) has 0 words.
#include <string>
int countWords(const std::string& s) {
// your code here
}
Write the implementation.
Scan the string tracking whether the previous character was whitespace. Each transition from whitespace to non-whitespace increments the word count. Handle multiple consecutive spaces and leading/trailing spaces correctly.
- ✗Counting spaces instead of transitions from space to non-space — fails on multiple spaces
- ✗Off-by-one: not counting the last word when string doesn't end with a space
- ✗Not handling the empty string case
- →How would you count unique words in a sentence?
- →How do you tokenise a string by a custom delimiter?
Contents
Task
Count the number of words in a sentence. Words are separated by whitespace (multiple spaces possible).
Solution
// Track space→non-space transitions
int countWords(const std::string& s) {
int count = 0; bool inSpace = true;
for (char c : s) {
if (std::isspace(c)) inSpace = true;
else if (inSpace) { ++count; inSpace = false; }
}
return count;
}
// Or: std::istringstream iss(s); std::string w; int n=0; while(iss>>w) ++n;
Key points
- Count transitions from whitespace to non-whitespace, not spaces.
istringstream >>is the idiomatic one-liner but allocates a string per word.
Contents