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.
Example 1
Input
s (string) =
hello worldReturns (int)
2Example 2
Input
s (string) =
one two threeReturns (int)
3Example 3
Input
s (string) =
CodeReturns (int)
1Example 4
Input
s (string) =
practice makes perfectReturns (int)
3Count every transition from a space into a non-space character. This avoids counting empty pieces created by repeated spaces.
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run