Adding Padding or Space to Display a String

by Edward 26 March 2011 17:19

A simple but unknown to many developers is the two methods for padding available in the String class. Using these two methods you can add padding to the left or to the right of a string to achieve a desired length. A real world example will be to add a '0' to a string value when a area code must be a specific length.

The two methods for this example is as follows:

String.PadLeft : Right aligns and pads a string from the left.
String.PadRight : Left aligns and pads a string from the right.

The following example shows how to indent strings using method for padding:

PadLeft:

string originalString = "123";
Console.WriteLine(originalString.PadLeft(3, '0'));

PadRight:

string originalString = "123";
Console.WriteLine(originalString.PadRight(3, '0'));

You should also understand that this does not format the original value, for example formatting a integer to decimal, but just 'append' a character either on the left or the right of the string.

Tags: , , ,

ASP.NET

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List