Beginner Level

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 0 when the string has no words.
  • Characters such as digits or punctuation may appear inside a word.
Example 1
Input:
s (string) = hello world
Return:
(int) 2
Example 2
Input:
s (string) = one two three
Return:
(int) 3
Example 3
Input:
s (string) = Code
Return:
(int) 1
Example 4
Input:
s (string) = practice makes perfect
Return:
(int) 3

Count every transition from a space into a non-space character. This avoids counting empty pieces created by repeated spaces.

Run your code to see the result.