Skip to content
Exercise · Strings and Arrays · lesson 6 of 6

Exercise: word count

Write a function int word_count(std::string_view s) that returns the number of words in the string s. A word is an unbroken run of characters other than the space ' '.

  • word_count("one") → 1
  • word_count("a b c") → 3
  • word_count(" two words ") → 2

Constraints: there can be any number of spaces at the start, at the end and between words. An empty string or a string of only spaces has no words, so the answer is 0.

word_count.cpp — cpp
cpp · 6 lines
Ctrl+Enter run · Esc leave editor