我在简单的文本输出报告中显示GUID和Numbers。如何保持每个字符串的长度“固定”。
例如。目前,这正是发生的事情。 (BAD)。
[WaWorkerHost.exe] +-----------------------------------------------------------+
[WaWorkerHost.exe] + RavenDb Initialization Report +
[WaWorkerHost.exe] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +
[WaWorkerHost.exe] + o) Tenant Id: 50f1bf7f-7936-4aa9-aeca-e47b1d61bb85 +
[WaWorkerHost.exe] + o) Number of Documents: 87 +
[WaWorkerHost.exe] + o) Number of Indexes: 5 +
[WaWorkerHost.exe] + o) Number of ~Stale Indexes: 0 +
[WaWorkerHost.exe] +-----------------------------------------------------------+
以及我在追求的......
[WaWorkerHost.exe] +-----------------------------------------------------------+
[WaWorkerHost.exe] + RavenDb Initialization Report +
[WaWorkerHost.exe] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +
[WaWorkerHost.exe] + o) Tenant Id: 50f1bf7f-7936-4aa9-aeca-e47b1d61bb85 +
[WaWorkerHost.exe] + o) Number of Documents: 87 +
[WaWorkerHost.exe] + o) Number of Indexes: 5 +
[WaWorkerHost.exe] + o) Number of ~Stale Indexes: 0 +
[WaWorkerHost.exe] +-----------------------------------------------------------+
喝彩!
(注意:guid是固定长度,因此该行具有'硬编码'空格。
答案 0 :(得分:5)
使用字符串格式:
static string BoxLine(int totalWidth, string format, params object[] args)
{
string s = String.Format(format, args);
return "+ " + s.PadRight(totalWidth - 4) + " +";
}
static string BoxStartEnd(int totalWidth)
{
return "+" + new String('-',totalWidth-2) + "+";
}
就像String.Format
一样调用它,但宽度在那里:
static void Main(string[] args)
{
const int BoxWidth = 40;
Console.WriteLine( BoxStartEnd(BoxWidth) );
Console.WriteLine( BoxLine(BoxWidth, "Does this work: {0} {1}", 42, 64) );
Console.WriteLine( BoxLine(BoxWidth, " -->Yep<--") );
Console.WriteLine( BoxStartEnd(BoxWidth) );
Console.Read();
}
输出:
+--------------------------------------+
+ Does this work: 42 64 +
+ -->Yep<-- +
+--------------------------------------+
答案 1 :(得分:3)
很难给出确切的解决方案,因为您没有提供源代码上下文。考虑下一个代码作为构建报告的示例:
var header = string.Format("Tenant Id: {0,-43}+", Guid.NewGuid());
var docCount = 87;
var indexesCount = 5;
var staleIndexesCount = 0;
string secondRow = string.Format("Number of Documents: {0,-33}+", docCount);
string thirdRow = string.Format("Number of Indexes: {0,-35}+", indexesCount);
string fourthRow = string.Format("Number of of ~Stale Indexes: {0,-25}+", staleIndexesCount);
Console.WriteLine (header);
Console.WriteLine (secondRow);
Console.WriteLine (thirdRow);
Console.WriteLine (fourthRow);
将打印:
Tenant Id: 90814671-a5e6-48c6-ad4a-a816e7611c65 +
Number of Documents: 87 +
Number of Indexes: 5 +
Number of of ~Stale Indexes: 0 +
答案 2 :(得分:0)
你必须知道你的目标是什么。
计算完毕后,使用PadRight
获取所需长度的字符串。您也可以使用string.Format
填充支持,但如果宽度不固定,则可能导致代码维护较少。