Start learning free

LESSON 2 OF 69 · PROJECTS: COMMAND-LINE TOOLS

cat -n in C#: Numbering Lines with StringBuilder and 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:

public string NumberedCat(List<string> lines)

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 by index, append a "\n" before every line except the first, then append the formatted line.

Use String.Format("{0,6}\t{1}", i + 1, lines[i]) to format each entry. The ,6 in {0,6} right-aligns the number in a field 6 characters wide.

The full solution:
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();
    }
}

STEP 1 OF 6
    Ctrl + Enter to check

    C# · PROJECTS: COMMAND-LINE TOOLS

    Cat V2 in C#, explained

    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

    1. Create the builder: StringBuilder sb = new StringBuilder();. It collects the output.
    2. Loop by index: for (int i = 0; i < lines.Count; i++). A list reports its length with Count, not Length. The index i is used twice, to pick the line and to compute the number.
    3. Test i > 0 and, inside that if, append "\n". Only rows after the first get a newline in front, so the output never starts or ends with one.
    4. Append the formatted row with String.Format("{0,6}\t{1}", i + 1, lines[i]). The numbers are 1-based while i starts at 0, hence i + 1.
    5. 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") gives 7 |x, which is not what this lesson wants.
    • {1} is argument 1, the line text, inserted as is. The \t between 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 + 1 is argument 0 and lines[i] is argument 1.
    • Interpolation works too. $"{i + 1,6}\t{lines[i]}" uses the same ,6 alignment syntax and builds the same row.
    • Append adds 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, with ToString().
    • StringBuilder lives in System.Text. In a file of your own, add using System.Text; and using System.Collections.Generic; for List<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 i instead of i + 1 numbers 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.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free