Easy 0 solved 0% acceptance

Count Words

Count the words in a sentence.

What you'll learn

  • Split text into words
  • Handle repeated and leading spaces
  • Count items in a list

Problem

A word is a run of non-space characters. Count the words in text; there may be extra spaces at the start, end or between words.

Implement count_words(text).

Input

text: The text to count.

Output

Return the number of words.

Constraints

0 ≤ length ≤ 10,000

Examples

Example 1
Input:
text = "Learn to code today"

Expected output:
expected = 4
Input:
std::string text = "Learn to code today";

Expected output:
long long expected = 4;
Input:
string text = "Learn to code today";

Expected output:
long expected = 4;

Explanation

Four words separated by spaces: 4.

Example 2
Input:
text = "   "

Expected output:
expected = 0
Input:
std::string text = "   ";

Expected output:
long long expected = 0;
Input:
string text = "   ";

Expected output:
long expected = 0;

Explanation

Only spaces, so there are no words: 0.

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

A word is any consecutive stretch of non-space characters.

Hint 2

Scan through the text and count transitions from spaces into letters.

Hint 3

Be careful with leading, trailing, and repeated spaces so you do not count empty runs.

Expected complexity

O(n) time, O(1) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.