Tuesday, February 17, 2009

Left pad using string.Format()

Maybe you already know this  but it took me many years to discover. 
You can left pad by adding   ,-X to the place holder in the format string.

Eg. the following lines:
Console.WriteLine(string.Format("  IsOK={0,-5} Name: {1,-20} xxx", true, "Klaus"));
Console.WriteLine(string.Format("  IsOK={0,-5} Name: {1,-20} xxx", false, "James"));
Console.WriteLine(string.Format("  IsOK={0,-5} Name: {1,-20} xxx", true, "RAU"));

produce the following output:




Nice isn’t it!

No comments: