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
- Create
var sb = "". The string grows row by row, so it must be avar. - Loop over the positions with
for i in 0..<lines.count. The half-open range stops beforelines.count, so the last index islines.count - 1. For an empty array the range is empty and the body never runs. - Test
i > 0. Only rows after the first need a newline in front of them. - Add the newline to
sbwith+=inside thatif. - Add the row: the number
i + 1formatted as%6ld, then"\t", thenlines[i], joined with+. The index starts at 0 but line numbers start at 1, hence the+ 1. - Return
sbafter 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:')". Withimport Foundationat the top of the file it works.- Why
ld. In the pattern,lmarks a 64-bit integer anddmeans decimal. Swift'sIntis 64 bits, so%ldmatches it. A plain%dreads only 32 bits:String(format: "%6d", 5_000_000_000)prints705032704, while%6ldprints5000000000. - The width is a minimum. A number with more than 6 digits isn't cut off.
1234567prints in full, and the row simply gets wider. - Without the width,
%ldwould print the bare number. Other flags change the padding:%-6daligns left and%06dpads with zeros. +and+=on strings.Stringis a value type, sosb += ...updates the variablesbthat 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, noti. - 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.
