
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.

Here we see an example of a C# program that declares four constant string literals and then loops over them in a foreach-statement. In each iteration of the loop, the PadLeft method is invoked twice. It is tested with two parameters, the first being the column width in characters and the second being the padding character. It is then tested with a single parameter, which yields a padding character of the space character.
Program that uses PadLeft [C#]
using System;
class Program
{
static void Main()
{
string[] words = { "1", "200", "Samuel", "Perls" }; // Input array
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
Right-aligning text. You can see the output of the program positions the strings on the right side of a ten-character wide block. In many scientific processing and financial applications, numbers are aligned to the right so that their decimal places are positioned in a single character column. The PadLeft method can be used for this, particularly if you control the number of decimal places with a call like value.ToString("0.00").
You can position text in more than one column. This is ideal for developing nontrivial console programs that provide specific numeric data. Note however that for user-facing applications, using more appealing user interfaces such as Windows Forms or Windows Presentation Foundation is preferable. On websites, HTML tables are preferable as well.
PadRight Aligns Strings
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. However, because the code does allocate a new string, you can enhance padding performance by using a cache of the padded strings, in Dictionary or array.

We can use the PadLeft method in the C# programming 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. We next noted the internal implementation of PadLeft in the .NET Framework, and provided some pointers about the appropriateness of text-based console layouts.
String Type