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
- Create
val sb = StringBuilder(). All rows go into it. - Loop with
for (i in lines.indices). The indices of a list are its positions 0, 1, 2 and so on. You needitwice: to read the line and to compute the number. - Test
i > 0. Only rows after the first need a newline in front of them. - Append
"\n"inside thatif. - 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 + 1andlines[i]. Positions start at 0, but line numbers start at 1. - 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):
| lines | result |
|---|---|
["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.formatcomes from Java. Kotlin callsjava.lang.String.formathere, and the format codes are Java's:%dfor integers,%sfor 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", butString.format("%6d", 1234567)gives"1234567": a number wider than 6 columns is never cut, it just pushes the tab further right. sb.appendreturns the builder, but the lesson ignores the result and calls it as a statement.lines.indicesis the range0 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
iinstead ofi + 1gives0as 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.
