Start learning free

LESSON 376 OF 415 · PROJECTS: COMMAND-LINE TOOLS

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

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  $

Build the result in a String variable and walk the lines by index. For each line, replace tabs with "^I", add the result, then add "$". Put a "\n" between lines.

replacingOccurrences(of:with:) swaps every occurrence: lines[i].replacingOccurrences(of: "\t", with: "^I") (it comes from Foundation, which the template already imports).

The full solution:
class Solution {
    func showAllCat(_ lines: [String]) -> String {
        var result = ""
        for i in 0..<lines.count {
            if i > 0 {
                result += "\n"
            }
            result += lines[i].replacingOccurrences(of: "\t", with: "^I")
            result += "$"
        }
        return result
    }
}

STEP 1 OF 7
    Ctrl + Enter to check

    Cat V3 in Swift

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