In the previous lesson, we discovered that our simple space-counting algorithm has fundamental flaws. Counting spaces doesn't accurately count words because:
Instead of counting spaces, let's think about what actually separates words: transitions between whitespace and non-whitespace characters.
Consider this string: "Hello World"
As we iterate through each character:
H - not a spacee - not a spacel - not a spacel - not a spaceo - not a space - is a space (state change!)W - not a space (state change! - this is where we enter a new word)o - not a spacer - not a spacel - not a spaced - not a spaceThe key insight is that every time we transition from a space to a non-space character, we're entering a new word.
We can track state changes using a boolean variable:
wasSpace)isSpace)wasSpace is true AND isSpace is false, we've entered a new wordwasSpace to equal isSpace for the next iterationLet's visualize this with multiple spaces: "Hello World" (two spaces)
Character | isSpace | wasSpace | Action
----------|---------|----------|--------
H | false | true* | wordCount++ (entering first word)
e | false | false | -
l | false | false | -
l | false | false | -
o | false | false | -
(space) | true | false | -
(space) | true | true | -
W | false | true | wordCount++ (entering second word)
o | false | false | -
r | false | false | -
l | false | false | -
d | false | false | -
*Note: We initialize wasSpace to true to correctly count the first word.
This algorithm handles all our edge cases:
Now it's your turn to implement this algorithm! You'll need to:
wordCount variablewasSpace variable (think about what the initial value should be)wasSpace for the next iterationRemember: you're looking for the transition from space to non-space!