C# PadLeft

Padding: right and left

PadLeft adds spaces to the left of strings. It can align strings to the right of a text column. It also handles characters other than spaces. The .NET Framework provides PadLeft—which eliminates the need for custom methods.

Example

First, this example program declares four constant string literals. It then loops over them in a foreach-statement. In each iteration of the loop, the PadLeft method is invoked twice.

String LiteralForeach

It is tested with two parameters. The first is the column width in characters and the second is the padding character. It is then tested with a single parameter—this yields a padding character of a space.

Program that uses PadLeft: C#

using System;

class Program
{
    static void Main()
    {
	string[] words = { "1", "200", "Samuel", "Perls" };
	foreach (string word in words) // Loop over words
	{
	    Console.WriteLine(word.PadLeft(10, '_')); // Write ten characters
	    Console.WriteLine(word.PadLeft(10)); // Write ten characters with space
	}
    }
}

Output

_________1
	 1
_______200
       200
____Samuel
    Samuel
_____Perls
     Perls
Arrow indicates movement

We see that the output of the program positions the strings on the right side of a ten-character wide block. In many applications, numbers are aligned to the right so that their decimal places are positioned in a single character column.

So:PadLeft can be used—you can control the number of decimal places with a call like value.ToString("0.00").

Discussion

Programming tip

You can position text in more than one column. This is ideal for developing console programs that provide specific numeric data. But for many applications, using more appealing user interfaces, such as Windows Forms, are preferable.

Tip:On websites HTML tables are often preferable to extra whitespace. The allow the text to flow and wrap.

PadRight

Implementation

Framework: NET

Let's examine how the PadLeft method is implemented in the .NET Framework internal code. The methods call into a PadHelper extern method, which means the code is written in a native computer language and is likely very optimized.

Tip:The code allocates a new string. This means can improve performance with a cache of the padded strings—in a Dictionary or array.

DictionaryArray

Summary

We used the PadLeft method in the C# language in a foreach-statement to right-align string values in an array. This method is helpful when developing columnar layouts of numeric data as with decimal places.


C#: String