Problem overview
This version of the cat tool adds the -n flag as a new method, NumberedCat. The previous version only joined the lines. Now every line gets a prefix: its 1-based number, right-aligned in a field 6 characters wide, then a tab character, then the line text. Blank lines are numbered too, and an empty list gives an empty string.
For ["hello", "world", "foo"] the result is this string, with \t standing for the tab:
" 1\thello\n 2\tworld\n 3\tfoo"
Each number is padded on the left with spaces until it is 6 characters wide, so 1 becomes five spaces followed by 1.
Approach
You need two things for every line: the line itself and its position, because the number is the position plus one. An index-based for loop gives you both. A foreach would give only the text.
The output also has a separator rule that is familiar from joining: a newline goes between rows, not after the last one. Inside a loop, the easy way to follow that rule is to write the newline before every row except the first. That is the check i > 0.
Since the rows are built piece by piece, the lesson uses a StringBuilder. A C# string never changes, so s += x in a loop creates a new string each time and copies all the text so far. A StringBuilder keeps one growing buffer and appends to it, and you turn it into a string once at the end with ToString().
Step by step
- Create the builder:
StringBuilder sb = new StringBuilder();. It collects the output. - Loop by index:
for (int i = 0; i < lines.Count; i++). A list reports its length withCount, notLength. The indexiis used twice, to pick the line and to compute the number. - Test
i > 0and, inside thatif, append"\n". Only rows after the first get a newline in front, so the output never starts or ends with one. - Append the formatted row with
String.Format("{0,6}\t{1}", i + 1, lines[i]). The numbers are 1-based whileistarts at 0, hencei + 1. - Return
sb.ToString()after the loop, so it runs once, when every row is in.
The solution in C#
class Solution {
public string NumberedCat(List<string> lines) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < lines.Count; i++) {
if (i > 0) {
sb.Append("\n");
}
sb.Append(String.Format("{0,6}\t{1}", i + 1, lines[i]));
}
return sb.ToString();
}
}
The format string is the part that needs explaining:
{0,6}means "argument 0, in a field 6 wide". A positive width right-aligns the value and pads on the left with spaces. A negative width would left-align:String.Format("{0,-6}|{1}", 7, "x")gives7 |x, which is not what this lesson wants.{1}is argument 1, the line text, inserted as is. The\tbetween the two placeholders is an ordinary tab character in the format string.- Arguments are numbered from 0 in the order you pass them. Here
i + 1is argument 0 andlines[i]is argument 1. - Interpolation works too.
$"{i + 1,6}\t{lines[i]}"uses the same,6alignment syntax and builds the same row. Appendadds to the builder and does not return a new string. You don't assign its result anywhere. The text is only read at the end, withToString().StringBuilderlives inSystem.Text. In a file of your own, addusing System.Text;andusing System.Collections.Generic;forList<string>.
Complexity
Time: O(total length). The loop visits each line once, and appending a row costs time proportional to its length. Appending to a StringBuilder is amortised constant time per character, so there is no repeated copying.
Space: O(total length). The builder and the final string hold all the text, plus the number prefix of each line.
Edge cases and common mistakes
- Starting at 0. Using
iinstead ofi + 1numbers the first line 0. - Numbering only non-blank lines. This flag numbers blank lines too.
["a", "", "b"]gives rows numbered 1, 2 and 3, and the second row is the number, a tab and nothing:" 1\ta\n 2\t\n 3\tb". - A trailing newline. Appending
"\n"after every row instead of before every row but the first leaves an extra newline at the end. - Spaces instead of a tab. The separator after the number is the single tab character, not spaces.
- The field is a minimum width, not a maximum. A number with more than 6 digits is never cut. With a list of 1,000,000 lines, line 999,999 is
"999999\tx"and line 1,000,000 is"1000000\tx", so that row is one character wider and the columns stop lining up. - An empty list. The loop never runs, the builder stays empty and
ToString()returns"". - Tabs inside a line. They are copied untouched.
["a\tb"]gives" 1\ta\tb".
Testing
["hello", "world", "foo"]gives" 1\thello\n 2\tworld\n 3\tfoo".["a", "", "b"]gives" 1\ta\n 2\t\n 3\tb".["only"]gives" 1\tonly", with no newline at all.[]gives"".- A list of ten lines
"L1"to"L10"ends with the row" 10\tL10": two digits, four spaces.
