Recap - Word Counter
Part of the Logic & Flow section of Coddy's Rust journey — lesson 34 of 66.
Challenge
EasyYou will receive a sentence as input. Count how many times each word appears in the sentence and store the counts in a hash map. Then print each unique word along with its count.
Requirements:
- Import
HashMapfromstd::collections - Create a mutable hash map with types
HashMap<String, i32> - Read the input sentence as a single line
- Split the sentence into individual words using
.split_whitespace() - For each word, use
.entry()with.or_insert(0)to initialize the count to0if the word doesn't exist - After using
.or_insert(0), increment the count by1for that word - After processing all words, iterate over the hash map and print each word with its count in the format:
[word]: [count]
Input:
- A single line containing a sentence with words separated by spaces (e.g.,
hello world hello rust world hello)
Output:
- One line for each unique word in the format:
[word]: [count] - The order of output lines may vary between test runs
Try it yourself
use std::collections::HashMap;
use std::io;
fn main() {
// Read input sentence
let mut sentence = String::new();
io::stdin().read_line(&mut sentence).expect("Failed to read line");
let sentence = sentence.trim();
// Create a mutable hash map to store word counts
let mut word_count: HashMap<String, i32> = HashMap::new();
// TODO: Write your code below
// Split the sentence into words and count each word
// Print each word with its count
}All lessons in Logic & Flow
1Advanced Control Flow
The 'match' ExpressionMatching Multiple ValuesMatching RangesThe 'if let' ExpressionLoops as ExpressionsRecap - Simple Command Parser4Grouping Data with Structs
What is a Struct?Structs OverviewAccessing Struct FieldsMutable StructsStructs as Function ParametersTuple StructsRecap - Create a Book Struct7Handling Errors with 'Result'
What is a 'Result'?Using 'match' with 'Result'is_ok() and is_err()Shortcuts: unwrap and expectThe Question Mark Operator '?'Parsing Strings to NumbersRecap - Safe Division Function10Closures & Anonymous Functions
What is a Closure?Defining a Simple ClosureClosures with ParametersCapturing the EnvironmentRecap - Simple Adder Closure2Introduction to Vectors
What is a Vector?Creating a VectorAdding Elements with pushAccessing Vector ElementsIterating Over a VectorMutable IterationRemoving ElementsRecap - Basic Score Tracker5Key-Value Pairs with Hash Maps
What is a Hash Map?Creating a Hash MapInserting Key-Value PairsAccessing ValuesIterating Over a Hash MapUpdating a ValueRemoving a PairRecap - Word Counter8Project: Simple Item Inventory
Project SetupAdding an ItemChecking StockSelling an ItemPutting it all together