Start learning free

LESSON 3 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat v3 in Rust: Show Tabs and Line Ends (-A)

Practice Read the full explanation

Now build the -A flag of the cat tool, as a new function. It makes whitespace visible: every tab character (\t) is replaced by the two characters ^I and every line ends with a literal $ marker (so trailing spaces become obvious). Lines are then joined with newlines.

Note: real cat -A also shows other control characters (such as ^M) and non-ASCII bytes; this version only handles tabs and line ends, like cat -T -E. A blank line becomes just $, and an empty list gives an empty string.

Function signature:

fn show_all_cat(lines: Vec<String>) -> String

Example:

Input: lines = ["hello\tworld", "foo"]

Output: "hello^Iworld$\nfoo$"

When printed:
hello^Iworld$
foo$

Another example (a blank line, trailing spaces):

Input: lines = ["a\t", "", "x  "]

Output: "a^I$\n$\nx  $"

When printed:
a^I$
$
x  $

Walk each line character by character with line.chars(). When you see a '\t', add "^I" to the transformed line; otherwise push the character itself. After the inner loop, add "$".

Inner transformation:
let mut transformed = String::new();
for c in line.chars() {
    if c == '\t' {
        transformed += "^I";
    } else {
        transformed.push(c);
    }
}
result.push_str(&(transformed + "$"));


The full solution:
impl Solution {
    fn show_all_cat(lines: Vec<String>) -> String {
        let mut result = String::new();
        for i in 0..lines.len() {
            if i > 0 {
                result += "\n";
            }
            let line = &lines[i];
            let mut transformed = String::new();
            for c in line.chars() {
                if c == '\t' {
                    transformed += "^I";
                } else {
                    transformed.push(c);
                }
            }
            result.push_str(&(transformed + "$"));
        }
        return result;
    }
}

STEP 1 OF 13
    Ctrl + Enter to check

    RUST · PROJECTS: COMMAND-LINE TOOLS

    Cat V3 in Rust, explained

    Problem overview

    Version 3 of the cat project adds the -A flag as a new function, show_all_cat(lines: Vec<String>) -> String. It makes whitespace visible: every tab character becomes the two characters ^I, and every line ends with a $ marker, so trailing spaces become obvious. The rows are joined with newlines as before.

    This version handles only tabs and line ends. Other control characters are left alone. A blank line becomes just $, and an empty list gives an empty string.

    For ["hello\tworld", "foo"] the result is "hello^Iworld$\nfoo$". For ["a\t", "", "x "] it is "a^I$\n$\nx $": the blank line shows as $ alone, and the two trailing spaces of x sit right in front of its $.

    Why the flag exists

    A tab and a run of spaces can look the same on screen, and trailing spaces are invisible altogether. Two lines that print identically can therefore differ, which is awkward when you are hunting for a stray tab in a file. Showing tabs as ^I and marking each line end with $ removes the guesswork: a space stays a space, a tab becomes two visible characters, and anything between the last visible character and the $ is trailing whitespace.

    Approach: rebuild each line character by character

    A string can't be edited in place when one character must turn into two, so each line is rebuilt. An empty transformed string grows as the code walks over the line: a tab appends ^I, any other character is copied. When the line is done, the $ goes on the end. The outer structure is the one from the earlier versions: loop over the lines by position and put a newline before every row except the first.

    Step by step

    1. Accumulator result, an empty mutable String.
    2. Outer loop for i in 0..lines.len(), with the if i > 0 check that appends a newline between rows.
    3. Name the line. let line = &lines[i]; borrows it, so the vector keeps ownership.
    4. Start the rebuilt line. let mut transformed = String::new(); belongs inside the outer loop, so every line starts from empty.
    5. Inner loop. for c in line.chars() yields one char at a time.
    6. The test. If c == '\t', append "^I"; otherwise transformed.push(c) copies the character.
    7. Close the row. After the inner loop, add transformed plus "$" to result with push_str.
    8. Return result.

    The solution in Rust

    impl Solution {
        fn show_all_cat(lines: Vec<String>) -> String {
            let mut result = String::new();
            for i in 0..lines.len() {
                if i > 0 {
                    result += "\n";
                }
                let line = &lines[i];
                let mut transformed = String::new();
                for c in line.chars() {
                    if c == '\t' {
                        transformed += "^I";
                    } else {
                        transformed.push(c);
                    }
                }
                result.push_str(&(transformed + "$"));
            }
            return result;
        }
    }
    

    Rust details worth knowing:

    • '\t' with single quotes is a char, one character, and "^I" with double quotes is a string. That is why the comparison uses single quotes while the append uses double quotes. push adds one char; += adds a string.
    • chars() walks Unicode characters, not bytes, so lines with accented letters or other non-ASCII text pass through unchanged. Indexing a string by byte position would be wrong for such text, and Rust doesn't allow line[j] on a string anyway.
    • transformed + "$" consumes transformed and returns the same String with $ appended. The & around the parenthesised sum lends that result to push_str, which copies it onto result.

    The difference between bytes and characters is easy to see: the string "é" has a len() of 2 bytes but one entry in chars(). Looping with chars() is what keeps such a character whole when it is copied with push.

    The work grows with the total number of characters, since each is looked at once, and the extra space is one rebuilt line at a time plus the result itself.

    A shorter alternative

    The same result comes from one call: line.replace('\t', "^I") + "$". For the line "a\tb\t" it produces "a^Ib^I$". The lesson uses the explicit character loop because it shows how a new string is assembled piece by piece, and the same loop is the starting point when each character needs its own rule.

    Both versions return a new string and leave the input vector unchanged, so the same lines can be reused afterwards. Whichever way it is written, a character that is not a tab must pass through untouched, including letters, spaces and non-ASCII text.

    Edge cases and common mistakes

    • Blank lines. The inner loop does nothing for "", so the row is just $.
    • Trailing spaces. They are copied as ordinary characters, so they appear before the $. That is the point of the marker.
    • Several tabs. Each one becomes its own ^I: ["\t\t"] gives "^I^I$".
    • Declaring transformed outside the outer loop. It would carry the previous line's text into the next row.
    • The marker once per line, not per character. It goes after the inner loop.
    • Empty list. No rows, so the result is "".
    • Only a tab was asked for. Other control characters, such as a carriage return, are copied as they are: this version does not mark them.

    Testing

    Each pair below is an input list and the string the function returns, with newlines and tabs written as escapes.

    ["hello\tworld", "foo"]  ->  "hello^Iworld$\nfoo$"
    ["a\t", "", "x  "]       ->  "a^I$\n$\nx  $"
    ["\t\t"]                 ->  "^I^I$"
    []                       ->  ""
    
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free