Implement the method countWords that returns the number of words in a string.
Count how many words appear in the input string. A word is a non-empty group of characters separated by one or more spaces.
The task is designed to test careful handling of edge cases, not only the most common input.
- Ignore leading, trailing, and repeated spaces.
- Return
0when the string has no words. - Characters such as digits or punctuation may appear inside a word.
Count every transition from a space into a non-space character. This avoids counting empty pieces created by repeated spaces.