Pybites Logo Rust Platform

tr: Translate and Delete Characters

Easy +2 pts
Unix tools 4/10

🎯 tr rewrites text one character at a time: tr 'a-z' 'A-Z' upper-cases, tr -d drops characters.

In Python you'd reach for str.replace, for example:

def translate(text: str, frm: str, to: str) -> str:
    return text.replace(frm, to)

def delete(text: str, ch: str) -> str:
    return text.replace(ch, "")

Rust has no "string-replace-with-a-char" shortcut here, you'll need to walk the characters yourself, because ...

char is not a one-character string

In Rust 'l' is a char - a single Unicode scalar value - while "l" is a &str. Note the difference in single vs double quotes used to denote each.

They're different types. .chars() turns a &str into an iterator of char:

for c in "hi".chars() { /* c: char */ }

Transform each char, then rebuild the string

.map() applies a function to every item. To rewrite characters, map each one to its replacement (or leave it unchanged):

let masked: String = "a1b2".chars().map(|c| if c.is_numeric() { '#' } else { c }).collect();
// "a#b#"

Keep only some chars

.filter() drops items that fail a test. The |&c| pattern copies the char out of the reference the closure receives:

let digits: String = "1-2-3".chars().filter(|&c| c != '-').collect();   // "123"

.collect::<String>()

An iterator of char collects straight into a String. The target type is inferred from the function's return type here, so a plain .collect() should be enough here.

Login to see the full task and start coding.

This is a premium exercise

Log in to unlock the full exercise and start coding.

Login to access this exercise