Start learning free

LESSON 25 OF 69 · PROJECTS: COMMAND-LINE TOOLS

Tr V1 in Rust: Swapping One Character

Practice Read the full explanation

Build a tiny version of the Unix tr command. Given a list of lines and two single characters fromChar and toChar, replace every occurrence of fromChar with toChar in each line, then return the lines joined by newline characters (\n).

Notes: from_char and to_char are single ASCII characters, taken literally (no escapes like \, no ranges). Upper and lower case are different characters. A line may be empty, and may not contain from_char at all.

Function signature:

fn tr(lines: Vec<String>, from_char: String, to_char: String) -> String

Example:

Input: lines = ["banana", "apple"], from_char = "a", to_char = "X"

Output: "bXnXnX\nXpple"

When printed:
bXnXnX
Xpple

Rust's str::replace swaps EVERY occurrence and returns a new String. Collect the translated lines into a Vec<String> and join them with result.join("\n").

The full solution:
impl Solution {
    fn tr(lines: Vec<String>, from_char: String, to_char: String) -> String {
        let mut result: Vec<String> = Vec::new();
        for line in &lines {
            result.push(line.replace(&from_char, &to_char));
        }
        return result.join("\n");
    }
}

STEP 1 OF 4
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Tr V1 in Rust, explained

    Problem overview

    The tr tool translates characters. In this first version, tr(lines, from_char, to_char) receives a list of lines and two strings, each holding a single ASCII character. It replaces every occurrence of from_char with to_char in every line and returns the lines joined by \n. The characters are taken literally, upper and lower case are different, and a line may be empty or may not contain from_char at all.

    For ["banana", "apple"] with "a" and "X", the result is "bXnXnX\nXpple". Every a is swapped, not only the first one in each line, and the ps and l in apple are untouched.

    Approach

    The work is the same for each line, so the shape is: translate each line, collect the results, join them. The translation of one line is a single call to the string method replace, which finds every occurrence of a pattern and returns a new string with the replacement in its place. Writing the character loop by hand is possible, but replace already does exactly the required job, and it does it on the whole line at once.

    Step by step

    1. Create result, an empty Vec<String>, with let mut, since lines will be added to it.
    2. Loop over the lines with for line in &lines. The & lends the vector to the loop, so each line is a reference to a String, one whole line, not one character.
    3. Push the translated line. line.replace(&from_char, &to_char) returns a new String, which goes straight into result. The original line is not changed. The two & lend the strings to replace instead of giving them away.
    4. After the loop, join the vector with "\n". The separator goes between lines only, so there is no newline after the last one.

    The solution in Rust

    impl Solution {
        fn tr(lines: Vec<String>, from_char: String, to_char: String) -> String {
            let mut result: Vec<String> = Vec::new();
            for line in &lines {
                result.push(line.replace(&from_char, &to_char));
            }
            return result.join("\n");
        }
    }
    

    Rust details:

    • Why the borrows. The loop runs once per line but uses from_char and to_char every time. Passing them by value would move them into the first call and leave nothing for the next iteration. Passing &from_char lends them, so every iteration can use them again.
    • for line in &lines against for line in lines. The first only borrows the vector. The second moves it into the loop, after which lines couldn't be used again. This function doesn't need lines afterwards, so both compile; the borrow is the more common habit.
    • replace returns a new string. Strings in Rust don't change under a method like this, and replace allocates a fresh String. The line in lines stays as it was.
    • Patterns. replace accepts a char, a &str or a &String as the pattern. Because the lesson's arguments are String values, &from_char is the natural way to pass them.

    Complexity

    Time: O(L), where L is the total number of characters in all lines, because each line is scanned once by replace and then copied into the joined result. Space: O(L) for the translated lines and the final string.

    Edge cases and common mistakes

    • Only the first occurrence. Some languages' replace functions change just the first match. Rust's replace changes all of them: "banana" becomes "bXnXnX".
    • Case. With "a" and "X", "Banana" becomes "BXnXnX". The B is a different character and is unchanged. An uppercase "A" would not match any of the lowercase letters.
    • Empty and unaffected lines. ["Banana", "", "xyz"] gives "BXnXnX\n\nxyz". The empty line stays as an empty line between two newlines.
    • Special characters are literal. ["a.b.c"] with "." and "-" gives "a-b-c". The dot is just a dot here, not a wildcard, because replace looks for the exact text.
    • Putting the join inside the loop. It runs once, after all lines are translated, so it sits outside the loop's braces.
    • Forgetting the & on the strings passed to replace gives two compile errors: a String isn't accepted as the pattern (the trait Pattern is not implemented for String), and the replacement must be a &str (expected &str, found String).

    Testing

    • ["banana", "apple"] with "a" and "X" gives "bXnXnX\nXpple".
    • ["Banana", "", "xyz"] with "a" and "X" gives "BXnXnX\n\nxyz".
    • ["a.b.c"] with "." and "-" gives "a-b-c".
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free