Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a number into a fixed string size, in .NET?

I'm displaying GUID's and Numbers in a simple text output report. How can i keep the length of each string 'fixed'.

eg. Currently, this is what is happening. (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] +-----------------------------------------------------------+

and what i'm after...

[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] +-----------------------------------------------------------+

cheers!

(note: the guid is a fixed length, so that line has 'hardcoded' spaces.

like image 777
Pure.Krome Avatar asked Feb 16 '23 15:02

Pure.Krome


1 Answers

With string formatting:

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) + "+";
}

Call it just like String.Format but with the width in there:

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();    
}

Output:

+--------------------------------------+
+ Does this work: 42 64                +
+  -->Yep<--                           +
+--------------------------------------+
  • String.PadRight
like image 188
Jonathon Reinhart Avatar answered Mar 04 '23 18:03

Jonathon Reinhart