Nobel Prize to anyone who can help me figure out if I'm doing this totally wrong. So what I'm trying to do is get an array of arrays of strings to print out as a table, e.g.
{ {"abcdefg", "hij"}, {"klm", "nopqrstuvwxyz"} }
----------------->
====================
abcdefg | hij
--------------------
klm | nopqrstu
| vwxyz
====================
where there's a constant determining the width of the table (in characters).
So my code is a complete monstrosity and doesn't work:
public static void PrintTable ( string[][] cells )
{
// Outputs content in cells matrix like
// =========================================
// cells[0][0] | cells[0][1]
// -----------------------------------------
// cells[1][0] | cells[1][1]
// -----------------------------------------
// cells[2][0] | cells[2][1]
// .
// .
// -----------------------------------------
// cells[n-1][0] | cells[n-1][1]
// ========================================
// Each cell must be able to hold at least 1 character inside
// 1 space of padding on the left and right
int linelen = OutputFormatter.OutputMaxLength; // copy of width (in characters) of lines being formatted
// Calculate widths of columns 1 and 2 (excluding the single space of padding on the
// left and right side of each):
int w1 = Math.Max(cells.Max(c => c[0].Length), linelen - 5);
int w2 = linelen - w1 - 1;
OutputFormatter.PrintChars('='); // prints a line of equals signs for the top border of the table
// print out rows:
foreach ( string[] row in cells )
{
// Make the strings corresponding to the first and second column have equal
// length by adding whitespace to the end of the shorter one:
int m1 = row[0].Length, m2 = row[1].Length;
String padding = new String(' ', Math.Abs(m1 - m2));
if ( m1 > m2 ) row[1] += padding;
else row[0] += padding;
// Print out content of row
for ( int i = 0, j = 0, n = row[0].Length; i < n && j < n; i += w1, j += w2 )
{
Console.WriteLine(" {0} | {1} ",
row[0].Substring(i,w1),
row[1].Substring(j,w2));
}
OutputFormatter.PrintChars('-'); // prints a line of dashes to separate rows
}
OutputFormatter.PrintChars('='); // prints a line of equals signs to form bottom border of table
}
Anyone have a 1-line solution for this? ;)
I've stepped through debugging and the exception is getting thrown after hitting
Console.WriteLine(" {0} | {1} ",
row[0].Substring(i,w1),
row[1].Substring(j,w2));
when I test with the input string
{
new string[] {"CompareLastTwo","Shows difference between friends lists of last two Facebook data files in repository"},
new string[] {"AddFriendList <DataFolderPath>", "blah blah blah"}
};
and all that has printed is
Can someone help me figure out the logical error(s) I am making here? And is there a way I can better leverage the .NET library to make this elegant, compact, efficient, clever and readable?