How To: Best way to draw table in console app (C#)(操作方法:在控制台应用程序中绘制表格的最佳方法 (C#))
问题描述
我有一个有趣的问题.想象一下,我有很多数据以非常快的间隔发生变化.我想在控制台应用程序中将该数据显示为表格.f.ex:
I have an interesting question. Imagine I have a lot of data changing in very fast intervals. I want to display that data as a table in console app. f.ex:
-------------------------------------------------------------------------
| Column 1 | Column 2 | Column 3 | Column 4 |
-------------------------------------------------------------------------
| | | | |
| | | | |
| | | | |
-------------------------------------------------------------------------
如何保持快速以及如何固定列宽?我知道如何在 java 中做到这一点,但我不知道它是如何在 C# 中完成的.
How to keep things fast and how to fix column widths ? I know how to do that in java, but I don't how it's done in C#.
推荐答案
你可以这样做:
static int tableWidth = 73;
static void Main(string[] args)
{
Console.Clear();
PrintLine();
PrintRow("Column 1", "Column 2", "Column 3", "Column 4");
PrintLine();
PrintRow("", "", "", "");
PrintRow("", "", "", "");
PrintLine();
Console.ReadLine();
}
static void PrintLine()
{
Console.WriteLine(new string('-', tableWidth));
}
static void PrintRow(params string[] columns)
{
int width = (tableWidth - columns.Length) / columns.Length;
string row = "|";
foreach (string column in columns)
{
row += AlignCentre(column, width) + "|";
}
Console.WriteLine(row);
}
static string AlignCentre(string text, int width)
{
text = text.Length > width ? text.Substring(0, width - 3) + "..." : text;
if (string.IsNullOrEmpty(text))
{
return new string(' ', width);
}
else
{
return text.PadRight(width - (width - text.Length) / 2).PadLeft(width);
}
}
这篇关于操作方法:在控制台应用程序中绘制表格的最佳方法 (C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:操作方法:在控制台应用程序中绘制表格的最佳方法 (C#)


基础教程推荐
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- rabbitmq 的 REST API 2022-01-01