Summary: in this tutorial, you will learn how to use the C# String PadLeft()
to pad a specified character on the left side of a string to achieve a desired length.
Introduction to the C# String PadLeft method
The String PadLeft()
method pads a space or a specified character on the left side of the current string to achieve a desired length.
In practice, the PadLeft()
method is useful for aligning strings or adding leading zeros to strings.
The following PadLeft()
method pads the current string with spaces on the left for a specified total length:
public string PadLeft (
int totalWidth
);
Code language: C# (cs)
In this syntax, the totalWith
is the desired length of the resulting string that includes the original string and additional padding spaces.
For example, the following program uses the PadLeft()
method to pad a message with three spaces on the left:
using static System.Console;
var message = "C# String PadLeft()";
var result = message.PadLeft(message.Length + 3);
WriteLine(result);
Code language: C# (cs)
Output:
C# String PadLeft()
Code language: plaintext (plaintext)
The PadLeft()
method has an overload that allows you to pad a string with a specified character on the left to get the resulting string with a specified length:
public string PadLeft (
int totalWidth,
char paddingChar
);
Code language: C# (cs)
In this syntax, the paddingChar
is the character for padding.
For example, the following program uses the PadLeft()
method to add leading zeros to a string so that the resulting string has a length of 6
:
using static System.Console;
var invoiceNumber = 1234;
var result = invoiceNumber.ToString().PadLeft(6, '0');
WriteLine(result);
Code language: C# (cs)
Output:
001234
Code language: C# (cs)
Summary
- Use the C# String
PadLeft()
method to pad a string with a specified character on the left to a desired length.