PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, September 20, 2022

[FIXED] How to iterate over string, and look up each value in a HashMap in Rust?

 September 20, 2022     hashmap, rust, string     No comments   

Issue

I would like to take an alphanumeric string, iterate character by character, and lookup each character in a HashMap.

Here is how I would do it in Python:

lookup: dict = {
    'J': 5,
    'H': 17,
    '4': 12
}

s: str = 'JH4'

looked_up: list[str] = [lookup[c] for c in s]
print(looked_up)
[5, 17, 12]

My attempt in Rust

use std::collections::HashMap;

fn main()
{

    let lookup: Hashmap<char, u32> = HashMap::from([
        ('J', 5),
        ('H', 17),
        ('4', 12)
    ]);

    let s = String::from("JH4");
    for c in s.chars()
    {
        // Stuck here
        // I would like to look up each character from s via the lookup key and return an array of
        // the values returned.
    }

}


Solution

chars() returns an iterator, so you can just map over each element, indexing the map:

use std::collections::HashMap;

fn main() {
    let lookup: HashMap<char, u32> = HashMap::from([
        ('J', 5),
        ('H', 17),
        ('4', 12)
    ]);

    let s = String::from("JH4");

    let looked_up: Vec<_> = s.chars().map(|c| lookup[&c]).collect();
    dbg!(looked_up);
}

This will panic if c is not a key of the map, so you may want to explicitly handle that case instead:

let looked_up: Vec<_> = s.chars().map(
    // return the value from the map, or if none exists,
    // return 0 by default
    |c| lookup.get(&c).unwrap_or(0)
).collect();


Answered By - PitaJ
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing