📅  最后修改于: 2023-12-03 15:23:33.271000             🧑  作者: Mango
在控制台 C# 中绘制表格是一个很常见的需求,它可以使输出内容更加规整、易于阅读。本文将介绍如何使用 C# 在控制台中绘制表格。
以下是实现在控制台 C# 中绘制表格的步骤:
int[,] tableData = new int[3, 3] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int columns = tableData.GetLength(1);
int rows = tableData.GetLength(0);
List<int> columnWidths = new List<int>();
int totalWidth = 0;
for (int i = 0; i < columns; i++)
{
int maxWidth = 0;
for (int j = 0; j < rows; j++)
{
int width = tableData[j, i].ToString().Length;
if (width > maxWidth)
{
maxWidth = width;
}
}
columnWidths.Add(maxWidth);
totalWidth += maxWidth;
}
Console.WriteLine(new string('-', totalWidth + columns - 1));
for (int i = 0; i < columns; i++)
{
Console.Write("| {0," + columnWidths[i] + "} ", tableData[0, i]);
}
Console.Write("|\n");
Console.WriteLine(new string('-', totalWidth + columns - 1));
for (int i = 1; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write("| {0," + columnWidths[j] + "} ", tableData[i, j]);
}
Console.Write("|\n");
Console.WriteLine(new string('-', totalWidth + columns - 1));
}
以下是在控制台 C# 中绘制表格的完整示例:
int[,] tableData = new int[3, 3] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int columns = tableData.GetLength(1);
int rows = tableData.GetLength(0);
List<int> columnWidths = new List<int>();
int totalWidth = 0;
for (int i = 0; i < columns; i++)
{
int maxWidth = 0;
for (int j = 0; j < rows; j++)
{
int width = tableData[j, i].ToString().Length;
if (width > maxWidth)
{
maxWidth = width;
}
}
columnWidths.Add(maxWidth);
totalWidth += maxWidth;
}
Console.WriteLine(new string('-', totalWidth + columns - 1));
for (int i = 0; i < columns; i++)
{
Console.Write("| {0," + columnWidths[i] + "} ", tableData[0, i]);
}
Console.Write("|\n");
Console.WriteLine(new string('-', totalWidth + columns - 1));
for (int i = 1; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
Console.Write("| {0," + columnWidths[j] + "} ", tableData[i, j]);
}
Console.Write("|\n");
Console.WriteLine(new string('-', totalWidth + columns - 1));
}
输出结果如下:
-----------------
| 1 | 2 | 3 |
-----------------
| 4 | 5 | 6 |
-----------------
| 7 | 8 | 9 |
-----------------
在控制台 C# 中绘制表格可以简化输出内容,并使其更加规整,便于阅读。上述示例演示了如何使用 C# 在控制台中绘制表格,您可以根据需要进行自定义。