Start learning free

LESSON 365 OF 404 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v3 — Show Special Chars (-A) in Go

Practice

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:

func showAllCat(lines []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. When you see a '\t', add "^I" to the transformed line; otherwise add the character itself. After the inner loop, add "$".

Inner transformation:
transformed := ""
for _, c := range line {
    if c == '\t' {
        transformed += "^I"
    } else {
        transformed += string(c)
    }
}
result += transformed + "$"


The full solution:
func showAllCat(lines []string) string {
    result := ""
    for i := 0; i < len(lines); i++ {
        if i > 0 {
            result += "\n"
        }
        line := lines[i]
        transformed := ""
        for _, c := range line {
            if c == '\t' {
                transformed += "^I"
            } else {
                transformed += string(c)
            }
        }
        result += transformed + "$"
    }
    return result
}

STEP 1 OF 13
    Ctrl + Enter to check

    Cat V3 in Go

    Keep going with GoAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free