Count Words in String
C++
Medium
4 views
Problem Description
Count total number of words in a sentence.
Real Life: Word count in document editors.
Step-by-Step Logic:
1. Count spaces + 1 = number of words
2. Or count transitions from space to non-space
3. Handle multiple spaces correctly
4. Return word count
Official Solution
void string_q8_count_words() {
string text = "C plus plus is awesome";
int wordCount = 0;
bool inWord = false;
for(int i = 0; i < text.length(); i++) {
if(text[i] != ' ' && !inWord) {
wordCount++;
inWord = true;
} else if(text[i] == ' ') {
inWord = false;
}
}
cout << "String: " << text << endl;
cout << "Total words: " << wordCount << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!