Start learning free

LESSON 3 OF 71 · PROJECTS: COMMAND-LINE TOOLS

cat -A in Swift: Showing Tabs and Line Ends

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:

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

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Cat V3 in Swift, explained

    Problem overview

    This version of cat makes whitespace visible, like the -A flag. The new function is showAllCat(_ lines: [String]) -> String. Every tab character in a line is replaced by the two characters ^I, and every line ends with a literal $. Lines are then joined with newlines, with no newline after the last one.

    Take ["a\t", "", "x "]. The first line has a trailing tab, the second is blank, and the third ends with two spaces. The result is the string "a^I$\n$\nx $", which prints as:

    a^I$
    $
    x  $
    

    The tab became ^I, the blank line became a lone $, and the $ after x sits two columns after the letter, so the trailing spaces can now be counted. That is the whole point of the marker: invisible characters at the end of a line become visible. An empty array gives an empty string.

    Real cat -A also shows other control characters and non-ASCII bytes. This version handles only tabs and line ends.

    Approach

    The structure matches the numbering version: build a result string row by row, with a newline before every row except the first. What changes is how each row is made. A row is the line with its tabs replaced, followed by $.

    Tabs are replaced inside the line before the marker is appended. The marker comes last on purpose: it has to follow every character of the line, including trailing spaces and tabs.

    Step by step

    1. Create var result = "" to collect the rows.
    2. Loop over the positions with for i in 0..<lines.count. The index tells you which line to read and whether it is the first.
    3. Test i > 0, because only rows after the first need a newline before them.
    4. Add "\n" to result inside that test.
    5. Add the line with its tabs swapped: lines[i].replacingOccurrences(of: "\t", with: "^I") returns a new string in which every tab is now the two characters ^I.
    6. Add the "$" marker after it, still inside the loop. It goes after the line text, so any trailing spaces appear just before it.
    7. Return result after the loop.

    The solution in Swift

        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
        }
    

    Swift details worth a closer look:

    • replacingOccurrences(of:with:) comes from Foundation. Without import Foundation, the compiler reports "value of type 'String' has no member 'replacingOccurrences'".
    • It returns a new string. Strings are value types and the original lines[i] is unchanged. The result must be used, which is why it is appended to result.
    • It replaces every occurrence, not just the first: "\t\t" becomes ^I^I.
    • Escapes in literals. "\t" in the source is a single tab character. "^I" is two ordinary characters, a caret and a capital I.
    • Two += lines. Appending the line and then the marker in two statements is equivalent to one longer expression, and it keeps each step easy to read.

    Complexity

    Each line is scanned once for tabs and copied once. Time and space are proportional to the total number of characters in the input, plus a small constant per line for the newline and the marker. The output is longer than the input by one character per tab and one or two per line.

    Edge cases and common mistakes

    • Blank lines. A line "" contributes just $. Skipping blank lines, or leaving the marker off them, loses a row.
    • Trailing spaces. They stay in the output, in front of the marker. Trimming them would defeat the purpose of the flag.
    • Several tabs in a row. ["\t\t"] gives "^I^I$".
    • The marker per line, not per result. $ is added inside the loop. Placing it after the loop would mark only the last line.
    • A newline after the last row. The newline goes before each row except the first, so the result never ends in a newline.
    • The empty array gives "", since the loop never runs and no marker is added.

    Testing

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