Start learning free

LESSON 2 OF 70 · PROJECTS: COMMAND-LINE TOOLS

cat v2 in Kotlin: Number Lines (-n) 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:

fun numberedCat(lines: List<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

Use a StringBuilder to accumulate the output. Iterate over lines.indices, append a "\n" before every line except the first, then append the formatted line.

Use String.format("%6d\t%s", i + 1, lines[i]) to format each entry. %6d right-aligns the integer in a 6-character field.

The full solution:
class Solution {
    fun numberedCat(lines: List<String>): String {
        val sb = StringBuilder()
        for (i in lines.indices) {
            if (i > 0) {
                sb.append("\n")
            }
            sb.append(String.format("%6d\t%s", i + 1, lines[i]))
        }
        return sb.toString()
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    KOTLIN · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in Kotlin, explained

    Problem overview

    The -n flag of cat puts a line number in front of every line. You write it as a new function, fun numberedCat(lines: List<String>): String, next to the plain version from the first step. Each output row has three parts:

    • the 1-based line number, right-aligned in a field 6 characters wide and padded with spaces on the left;
    • a tab character (\t);
    • the original line.

    Rows are joined with newlines, blank lines are numbered like any other, and an empty list gives an empty string. For ["hello", "world", "foo"] the result is " 1\thello\n 2\tworld\n 3\tfoo".

    Approach

    Each row needs its position, so a loop over the indices is a natural fit. The newline goes between rows, not after the last one, so you add one before every row except the first. A StringBuilder collects the pieces. It builds one long string by appending to a buffer, which is cheaper than creating a new string for every concatenation. The row itself comes from String.format, which fills a pattern with values.

    Step by step

    1. Create val sb = StringBuilder(). All rows go into it.
    2. Loop with for (i in lines.indices). The indices of a list are its positions 0, 1, 2 and so on. You need i twice: to read the line and to compute the number.
    3. Test i > 0. Only rows after the first need a newline in front of them.
    4. Append "\n" inside that if.
    5. Append the row. The pattern "%6d\t%s" means: a whole number in 6 columns, right-aligned (%6d), then a tab, then a string (%s). The values follow in order: i + 1 and lines[i]. Positions start at 0, but line numbers start at 1.
    6. Return sb.toString() after the loop, once every row is in.

    The solution in Kotlin

    class Solution {
        fun numberedCat(lines: List<String>): String {
            val sb = StringBuilder()
            for (i in lines.indices) {
                if (i > 0) {
                    sb.append("\n")
                }
                sb.append(String.format("%6d\t%s", i + 1, lines[i]))
            }
            return sb.toString()
        }
    }
    

    Calling it gives these results (\n and \t written out):

    linesresult
    ["hello", "world", "foo"]" 1\thello\n 2\tworld\n 3\tfoo"
    ["x", "", "y"]" 1\tx\n 2\t\n 3\ty"
    []""

    With ten lines, the tenth row starts with 10: four spaces and two digits fill the 6 columns, so the numbers stay lined up.

    Kotlin details worth knowing

    • String.format comes from Java. Kotlin calls java.lang.String.format here, and the format codes are Java's: %d for integers, %s for strings, and a number before the letter is the minimum width. "%6d" pads with spaces on the left; "%-6d" would pad on the right.
    • The width is a minimum. String.format("%6d", 42) gives " 42", but String.format("%6d", 1234567) gives "1234567": a number wider than 6 columns is never cut, it just pushes the tab further right.
    • sb.append returns the builder, but the lesson ignores the result and calls it as a statement.
    • lines.indices is the range 0 until lines.size. For an empty list the range is empty and the loop body never runs.

    Edge cases and common mistakes

    • Numbering from 0. Passing i instead of i + 1 gives 0 as the first number.
    • A newline after the last row. Appending "\n" at the end of every iteration leaves a trailing newline that the expected text doesn't have.
    • Skipping blank lines. They are numbered too: a blank second line gives " 2\t", a number and a tab with nothing after them.
    • Spaces instead of a tab. The separator between number and text is one tab character, \t.
    • The wrong width. Five or seven columns changes every row, so the output no longer matches.
    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free