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
Returns (int) 2

Example 2

Input
s (string) = one two three
Returns (int) 3

Example 3

Input
s (string) = Code
Returns (int) 1

Example 4

Input
s (string) = practice makes perfect
Returns (int) 3

Count 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

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.