w3resource

Rust Character Frequency Counter

Rust Arrays: Exercise-8 with Solution

Write a Rust program to count the frequency of characters in a string and store the result in a HashMap.

Sample Solution:

Rust Code:

use std::collections::HashMap; // Import the HashMap type from the standard library

fn main() {
    // Define the input string
    let input_string = "w3resource.com";

    // Create an empty HashMap to store character frequencies
    let mut char_frequency: HashMap<char, usize> = HashMap::new(); // Key: char, Value: usize

    // Iterate over each character in the input string
    for ch in input_string.chars() {
        // Check if the character is already present in the HashMap
        // If it is present, increment its frequency count
        // If it is not present, insert it into the HashMap with a frequency count of 1
        let count = char_frequency.entry(ch).or_insert(0);
        *count += 1;
    }

    // Print the HashMap containing character frequencies
    println!("Character Frequencies: {:?}", char_frequency);
}

Output:

Character Frequencies: {'e': 2, 'r': 2, '3': 1, 's': 1, 'c': 2, 'm': 1, '.': 1, 'u': 1, 'w': 1, 'o': 2}

Explanation:

Here is a brief explanation of the above Rust code:

  • use std::collections::HashMap;: This line imports the "HashMap" type from the standard library, allowing us to use HashMaps in our code.
  • fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
  • let input_string = "w3resource.com";: This line defines the input string for which we want to count the frequency of characters.
  • let mut char_frequency: HashMap<char, usize> = HashMap::new();: This line creates an empty HashMap named char_frequency with keys of type char and values of type usize to store the frequency of characters.
  • for ch in input_string.chars() { ... }: This line starts a loop to iterate over each character (ch) in the input string using the chars() method.
  • let count = char_frequency.entry(ch).or_insert(0);: This line checks if the current character ch is already present in the char_frequency HashMap. If it is present, it returns a mutable reference to its frequency count (count). If it is not present, it inserts the character into the HashMap with a frequency count of 0 and returns a mutable reference to the newly inserted value.
  • *count += 1;: This line increments the frequency count of the current character by 1 using the mutable reference obtained in the previous step.
  • println!("Character Frequencies: {:?}", char_frequency);: Finally this line prints the HashMap containing the frequency of characters after iterating through the entire input string.

Rust Code Editor:

Previous: Rust HashMap Merging & Printing.
Next: Rust HashMap Tutorial: String Keys, Integer Vectors.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/rust/collections_and_data_structures/rust-hashmaps-exercise-8.php