可以使用格式化字符串来实现文本对齐。具体方法如下:

  1. 定义一个格式化字符串,使用占位符来表示每列的宽度和对齐方式。

例如,如果要输出两列,第一列宽度为10,左对齐,第二列宽度为5,右对齐,格式化字符串可以定义为:

string format = "{0,-10}{1,5}";

其中,-10表示左对齐并且宽度为10,5表示右对齐并且宽度为5。

  1. 使用string.Format方法来格式化输出字符串,将要输出的每列数据作为参数传入。

例如:

string col1 = "Column 1"; int col2 = 12345; string output = string.Format(format, col1, col2);

  1. 输出格式化后的字符串。

例如:

Console.WriteLine(output);

完整示例代码如下:

string format = "{0,-10}{1,5}"; string col1 = "Column 1"; int col2 = 12345; string output = string.Format(format, col1, col2); Console.WriteLine(output)

c# 怎么让输出的文本每列对齐

原文地址: https://www.cveoy.top/t/topic/gJFA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录