Start learning free

LESSON 2 OF 71 · PROJECTS: COMMAND-LINE TOOLS

cat -n in Swift: Numbering Lines with String(format:)

Practice Read the full explanation

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

    SWIFT · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in Swift, explained

    Problem overview

    The first version of cat joined lines with newlines. This one adds the -n flag as a new function, numberedCat(_ lines: [String]) -> String. Every line is printed with its 1-based number, right-aligned in a field 6 characters wide, then a tab, then the line text. Blank lines are numbered too, and an empty array gives an empty string.

    For ["hello", "world", "foo"] the result is this string, where \t is a tab:

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

    Each number is padded with spaces on the left until it fills 6 columns, so 1 becomes five spaces and a 1. As in version 1, the newlines go between rows, with none after the last row.

    Approach

    The function builds the result one row at a time. For each line it needs two things: the line's position, to compute the number, and the text itself. A loop over the indices 0..<lines.count provides both, since lines[i] is the text and i + 1 is the number.

    The row separator needs care. If every row ended with "\n", the result would finish with an extra newline. So a newline is added before every row except the first, which is the case i == 0.

    The number is formatted with String(format:), which builds text from a pattern the way printf does in C. The pattern %6ld means "an integer, in a field of at least 6 columns, right-aligned".

    Step by step

    1. Create var sb = "". The string grows row by row, so it must be a var.
    2. Loop over the positions with for i in 0..<lines.count. The half-open range stops before lines.count, so the last index is lines.count - 1. For an empty array the range is empty and the body never runs.
    3. Test i > 0. Only rows after the first need a newline in front of them.
    4. Add the newline to sb with += inside that if.
    5. Add the row: the number i + 1 formatted as %6ld, then "\t", then lines[i], joined with +. The index starts at 0 but line numbers start at 1, hence the + 1.
    6. Return sb after the loop, so it runs once, when every row is in.

    The solution in Swift

        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
        }
    

    Swift details worth a closer look:

    • String(format:) comes from Foundation. A file that doesn't import Foundation can't use it: the compiler reports "incorrect argument labels in call (have 'format:_:', expected 'repeating:count:')". With import Foundation at the top of the file it works.
    • Why ld. In the pattern, l marks a 64-bit integer and d means decimal. Swift's Int is 64 bits, so %ld matches it. A plain %d reads only 32 bits: String(format: "%6d", 5_000_000_000) prints 705032704, while %6ld prints 5000000000.
    • The width is a minimum. A number with more than 6 digits isn't cut off. 1234567 prints in full, and the row simply gets wider.
    • Without the width, %ld would print the bare number. Other flags change the padding: %-6d aligns left and %06d pads with zeros.
    • + and += on strings. String is a value type, so sb += ... updates the variable sb that the function owns, and callers' data is never touched.

    Complexity

    The loop runs once per line and formats one number per line. Time and space are proportional to the total size of the output, which is the sum of the line lengths plus the 7 characters of number and tab and the newline added to each row.

    Edge cases and common mistakes

    • Numbering from 0. The first line is number 1, so the formatted value is i + 1, not i.
    • A trailing newline. Adding "\n" after every row, instead of before every row but the first, would put an extra newline at the end of the result.
    • Blank lines are numbered. ["", "x"] gives " 1\t\n 2\tx": the first row has its number and tab but no text.
    • The empty array gives "", because the loop body never runs.
    • Spaces instead of a tab. The separator between the number and the text is the tab character "\t", not spaces. Printed, a tab can look like spaces, but the result is a different string.

    Testing

    For twelve lines l1 to l12, the printed output shows how the numbers keep their right edge when they grow from one to two digits:

         1	l1
         2	l2
         3	l3
         4	l4
         5	l5
         6	l6
         7	l7
         8	l8
         9	l9
        10	l10
        11	l11
        12	l12
    

    The other inputs worth trying are [], which gives "", and ["", "x"], shown above.

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