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();
}
}
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
