📖 Scenario: Imagine you are analyzing a short message to find out how often each letter appears. This is useful in text analysis, like counting letters in a secret code or checking letter usage in a note.
🎯 Goal: You will build a program that counts how many times each character appears in a given text string.
📋 What You'll Learn
Create a string variable with a specific message
Create an empty dictionary (HashMap) to store character counts
Use a loop to count each character's frequency
Print the final character counts
💡 Why This Matters
🌍 Real World
Counting character frequency is useful in text analysis, cryptography, and data compression.
💼 Career
Understanding how to count and store frequencies helps in roles involving data processing, software development, and algorithm design.
Progress0 / 4 steps
1
Create the message string
Create a variable called message and set it to the string "hello rust".
DSA Rust
Hint
Use let message = "hello rust"; to create the string.
2
Create an empty HashMap for counts
Create a mutable variable called char_counts and set it to an empty HashMap<char, usize>. Add use std::collections::HashMap; at the top if needed.
DSA Rust
Hint
Use let mut char_counts: HashMap = HashMap::new(); to create the empty map.
3
Count each character in the message
Use a for loop with variable ch to iterate over message.chars(). Inside the loop, update char_counts by increasing the count for ch by 1 using entry(ch).and_modify(|count| *count += 1).or_insert(1).
DSA Rust
Hint
Use for ch in message.chars() and update counts with char_counts.entry(ch).and_modify(|count| *count += 1).or_insert(1);
4
Print the character counts
Print the char_counts HashMap using println!("{:?}", char_counts); to show the frequency of each character.
DSA Rust
Hint
Use println!("{:?}", char_counts); to print the map.
Practice
(1/5)
1. What does character frequency counting mean in simple terms?
easy
A. Counting how many times each character appears in a string
B. Sorting characters alphabetically
C. Replacing characters with numbers
D. Removing duplicate characters from a string
Solution
Step 1: Understand the meaning of frequency counting
Frequency counting means counting how often each item appears.
Step 2: Apply to characters in a string
For characters, it means counting how many times each character shows up in the string.
Final Answer:
Counting how many times each character appears in a string -> Option A
Quick Check:
Frequency counting = Counting occurrences [OK]
Hint: Think: How many times does each letter show up? [OK]
Common Mistakes:
Confusing frequency counting with sorting
Thinking frequency means replacing characters
Mixing frequency with removing duplicates
2. Which Rust code snippet correctly initializes an empty frequency map for characters?
easy
A. let mut freq = std::collections::HashMap::new();
B. let freq = Vec::new();
C. let freq = String::new();
D. let mut freq = 0;
Solution
Step 1: Identify the data structure for frequency counting
Frequency counting needs a map to store character keys and counts as values.
Step 2: Check Rust syntax for creating an empty map
HashMap::new() creates an empty map; mut allows adding entries.
Final Answer:
let mut freq = std::collections::HashMap::new(); -> Option A
Quick Check:
Empty map initialization = HashMap::new() [OK]
Hint: Use HashMap::new() for empty maps in Rust [OK]
Common Mistakes:
Using Vec or String instead of HashMap
Not making the map mutable
Initializing with a number instead of a map
3. What is the output of this Rust code counting characters in "hello"?
use std::collections::HashMap;
fn main() {
let text = "hello";
let mut freq = HashMap::new();
for ch in text.chars() {
*freq.entry(ch).or_insert(0) += 1;
}
println!("{:?}", freq);
}
medium
A. {"h": 1, "e": 1, "l": 1, "o": 1}
B. {"h": 1, "e": 1, "l": 3, "o": 1}
C. {"h": 1, "e": 1, "l": 2, "o": 1}
D. {"h": 0, "e": 0, "l": 0, "o": 0}
Solution
Step 1: Count each character in "hello"
Characters: h(1), e(1), l(2), o(1).
Step 2: Check code logic for counting
Code increments count for each character correctly using or_insert(0) and += 1.
Final Answer:
{"h": 1, "e": 1, "l": 2, "o": 1} -> Option C
Quick Check:
Count 'l' twice, others once [OK]
Hint: Count letters carefully, 'l' appears twice in 'hello' [OK]
Common Mistakes:
Counting 'l' only once
Confusing keys and values in map
Assuming zero counts for characters
4. Find the error in this Rust code for counting characters:
use std::collections::HashMap;
fn main() {
let text = "abcabc";
let mut freq = HashMap::new();
for ch in text.chars() {
freq.insert(ch, freq[&ch] + 1);
}
println!("{:?}", freq);
}
medium
A. HashMap is not mutable
B. println! macro is missing semicolon
C. text.chars() is incorrect syntax
D. Using freq[&ch] causes panic if key not present
Solution
Step 1: Understand freq[&ch] usage
freq[&ch] tries to get value for key ch but panics if key missing.
Step 2: Identify missing key problem
On first occurrence, key ch is missing, so freq[&ch] causes runtime panic.
Final Answer:
Using freq[&ch] causes panic if key not present -> Option D
Quick Check:
Accessing missing key with [] panics [OK]
Hint: Use or_insert(0) to avoid missing key panic [OK]
Common Mistakes:
Assuming freq[&ch] returns 0 if key missing
Not making HashMap mutable
Thinking text.chars() is wrong syntax
5. Given a string, how can you count only alphabetic characters ignoring digits and symbols in Rust?
Choose the best approach.
hard
A. Count all characters including digits and symbols
B. Use chars().filter(|c| c.is_alphabetic()) and count frequencies
C. Convert string to bytes and count all bytes
D. Replace digits with spaces then count all characters
Solution
Step 1: Filter only alphabetic characters
Use filter with is_alphabetic() to keep letters only.
Step 2: Count frequencies on filtered characters
Count frequencies on filtered chars to ignore digits/symbols.
Final Answer:
Use chars().filter(|c| c.is_alphabetic()) and count frequencies -> Option B
Quick Check:
Filter letters first, then count [OK]
Hint: Filter letters with is_alphabetic() before counting [OK]
Common Mistakes:
Counting digits and symbols by mistake
Using bytes which may split characters wrongly
Replacing digits but forgetting symbols
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.