Start learning free

LESSON 375 OF 415 · PROJECTS: COMMAND-LINE TOOLS

CLI Tool: cat v2 — Number Lines (-n) in Swift

Practice

Now build the -n flag of the cat tool, as a new function. It prints every line preceded by its 1-based line number, right-aligned in 6 columns, then a tab character, then the line text. Blank lines are numbered too, and an empty list gives an empty string.

Function signature:

func numberedCat(_ lines: [String]) -> String

Format per line: the line number right-aligned in a field 6 characters wide (padded with spaces on the left), then a literal tab (\t), then the original line.

Example:

Input: lines = ["hello", "world", "foo"]

Output:
"     1\thello\n     2\tworld\n     3\tfoo"

When printed:
     1	hello
     2	world
     3	foo

Build the result in a String variable. Iterate by index and add a "\n" before every line except the first, then add the formatted line.

String(format: "%6ld", i + 1) right-aligns the number in 6 columns; then add "\t" and lines[i].

The full solution:
class Solution {
    func numberedCat(_ lines: [String]) -> String {
        var sb = ""
        for i in 0..<lines.count {
            if i > 0 {
                sb += "\n"
            }
            sb += String(format: "%6ld", i + 1) + "\t" + lines[i]
        }
        return sb
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    Cat V2 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