Skip to content
Exercise · Collections · lesson 9 of 10

Exercise: word count

Write a function fn word_count(text: &str) -> HashMap<String, usize> that counts how many times each word occurs in the text text. The key in the map is a word, the value is how many times it occurred.

  • word_count("red blue red") → {"red": 2, "blue": 1}
  • word_count("one") → {"one": 1}
  • word_count("") → {}

Constraints: words are Latin or Cyrillic; they are separated by one or more spaces, which may also stand at the start and at the end of the text; case matters, so Red and red are different words; an empty text has no words.

Do not add extra use lines unless the task says so explicitly.

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