Start learning free

LESSON 2 OF 70 · PROJECTS: COMMAND-LINE TOOLS

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

def 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 "%6d\t%s".format(i + 1, lines(i)) to format each entry. %6d right-aligns the integer in a 6-character field.

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

STEP 1 OF 6
    Ctrl + Enter to check

    SCALA · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in Scala, explained

    Problem overview

    This version adds the -n flag of cat as a new function, numberedCat. It takes a List[String] and returns the lines joined with newlines, each one preceded by its 1-based number. The number is right-aligned in a field 6 characters wide, followed by a tab character and then the line text. Blank lines are numbered too, and an empty list gives an empty string.

    For ["hello", "world", "foo"] the result is " 1\thello\n 2\tworld\n 3\tfoo". Each number is padded with spaces on the left until it is 6 characters wide, so 1 is preceded by five spaces.

    Approach

    Two things are needed for each row: the line's position and the line. Looping over lines.indices gives the positions 0, 1, 2 and so on, and lines(i) gives the line at a position. The number shown is i + 1, because people count lines from 1 while Scala counts positions from 0.

    For the row layout, Scala strings have a format method that works like C's printf: a pattern with placeholders, followed by the values. In "%6d\t%s", %6d prints an integer in a field 6 characters wide (padding on the left), \t is a tab, and %s prints a string.

    The rows must be separated by newlines, but without a newline at the end. The loop therefore adds a newline before every row except the first. A StringBuilder collects the pieces, which is cheaper than creating a new string for every concatenation.

    Step by step

    1. Create a StringBuilder named sb to hold the output.
    2. Loop over the positions with for (i <- lines.indices), since both the number and the line are needed.
    3. Check i > 0. Only rows after the first need a separator in front of them.
    4. Append a newline inside that check.
    5. Append the row. Format i + 1 and lines(i) with the pattern "%6d\t%s". Scala indexes a list with round brackets.
    6. Return the text with sb.toString(), after the loop.

    The solution in Scala

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

    Details worth knowing:

    • "%6d\t%s".format(i + 1, lines(i)) calls format on the pattern string, and the values after it fill the placeholders in order. %d needs an integer and %s takes any value as text.
    • The width in %6d is a minimum. A number with more than 6 digits is not cut: "%6d\t%s".format(1234567, "wide") gives "1234567\twide".
    • lines.indices is a range of the valid positions, 0 until lines.size. For an empty list it is empty, so the loop body never runs.
    • lines(i) on a List walks from the head to position i, so a long list is slower to index than an array. For lines read from a file this is fine for learning.

    Edge cases and common mistakes

    • Starting the number at 0. Using i instead of i + 1 numbers the first line 0.
    • A newline after the last row. Appending the newline after every row, instead of before every row but the first, leaves a trailing \n.
    • Blank lines. They are numbered like any other: List("a", "", "b") gives " 1\ta\n 2\t\n 3\tb", where row 2 is just the number and the tab.
    • Empty list. The loop never runs and the result is "".
    • Wrong alignment. Number padding comes from the format width. Using %-6d would left-align instead.

    Testing

    InputResult
    List("hello", "world", "foo")" 1\thello\n 2\tworld\n 3\tfoo"
    List("a", "", "b")" 1\ta\n 2\t\n 3\tb"
    List()""

    With ten lines x1 to x10, the last row is " 10\tx10": four spaces, then the number.

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