string.PadLeft() / PadRight()
| Since: | C# 1.0(2002) |
|---|
The PadLeft() method pads a string on the left, PadRight() pads it on the right, and string.Format() creates a formatted string — all to produce a string of a specified length or layout.
Syntax
// Returns a string padded on the left with spaces (or a specified character) to reach totalWidth. str.PadLeft(int totalWidth) str.PadLeft(int totalWidth, char paddingChar) // Returns a string padded on the right with spaces (or a specified character) to reach totalWidth. str.PadRight(int totalWidth) str.PadRight(int totalWidth, char paddingChar) // Returns a string with format placeholders replaced by the given arguments. string.Format(string format, object arg0, ...)
Method List
| Method | Description |
|---|---|
| PadLeft(int totalWidth) | Returns a string of totalWidth characters, padded with spaces on the left. If the original string is already totalWidth or longer, it is returned unchanged. |
| PadLeft(int totalWidth, char paddingChar) | Returns a string of totalWidth characters, padded on the left with paddingChar. |
| PadRight(int totalWidth) | Returns a string of totalWidth characters, padded with spaces on the right. |
| PadRight(int totalWidth, char paddingChar) | Returns a string of totalWidth characters, padded on the right with paddingChar. |
| string.Format(string format, ...) | Returns a string where placeholders such as {0} and {1} are replaced with the corresponding argument values. |
Sample Code
Program.cs
using System;
// Use PadLeft() to right-align numbers
for (int i = 1; i <= 5; i++) {
string line = i.ToString().PadLeft(3);
Console.WriteLine(line);
}
// Use PadLeft() to zero-pad a number
string code = "42".PadLeft(6, '0');
Console.WriteLine(code); // 000042
This produces the following output:
dotnet run 1 2 3 4 5 000042
Formatting a Table with PadRight()
PadRight() left-aligns columns of text. It is useful for formatting text output as a table.
TableFormat.cs
using System;
// Use PadRight() to left-align text
string[] members = { "Yagami Iori", "Kusanagi Kyo", "Terry Bogard" };
int[] scores = { 95, 88, 72 };
for (int i = 0; i < members.Length; i++) {
Console.WriteLine(members[i].PadRight(14) + scores[i] + " pts");
}
// Use string.Format() to build a formatted string
string message = string.Format("{0}'s score is {1} points.", "Yagami Iori", 95);
Console.WriteLine(message);
// Numeric format specifiers (percentage, etc.)
double discountRate = 0.1567;
Console.WriteLine(string.Format("Discount rate: {0:P1}", discountRate)); // Discount rate: 15.7%
This produces the following output:
dotnet run Yagami Iori 95 pts Kusanagi Kyo 88 pts Terry Bogard 72 pts Yagami Iori's score is 95 points. Discount rate: 15.7%
Format Specifier Strings
Numeric format specifier strings such as ToString("D6") provide a concise way to zero-pad or set the number of digits. They can also be used with string interpolation.
FormatString.cs
using System;
// Zero-padding with ToString() format specifiers (alternative to PadLeft)
Console.WriteLine(42.ToString("D6")); // 000042
Console.WriteLine(255.ToString("X4")); // 00FF (hexadecimal, 4 digits)
Console.WriteLine(3.14.ToString("F2")); // 3.14 (2 decimal places)
// Format specifiers also work with string interpolation
double price = 1234.5;
Console.WriteLine($"Price: {price:N0}"); // Price: 1,235
Console.WriteLine($"Rate: {0.756:P1}"); // Rate: 75.6%
Console.WriteLine($"Code: {42:D6}"); // Code: 000042
This produces the following output:
dotnet run 000042 00FF 3.14 Price: 1,235 Rate: 75.6% Code: 000042
Common Mistakes
Common Mistake: Original String Longer Than totalWidth
PadLeft() and PadRight() return the original string unchanged — without truncating it — if it is already at or beyond totalWidth. This can break column alignment when values are longer than expected.
pad_sample.cs
using System; // Original string longer than totalWidth is returned unchanged string longStr = "ABCDEFGHIJ"; // 10 characters Console.WriteLine(longStr.PadLeft(5)); // ABCDEFGHIJ (not truncated) Console.WriteLine(longStr.PadRight(5)); // ABCDEFGHIJ (not truncated) // To handle overflow, truncate with Substring() first string truncated = longStr.Substring(0, Math.Min(5, longStr.Length)); Console.WriteLine(truncated); // ABCDE
This produces the following output:
dotnet run ABCDEFGHIJ ABCDEFGHIJ ABCDE
Notes
In modern C#, string interpolation ($"{variable}") is often preferred over string.Format(). Format specifiers such as :P1 and :D6 can also be used with string interpolation in the form $"{value:format}".
To zero-pad a number with PadLeft(), you can also use a numeric format string such as number.ToString("D6").
For splitting and joining strings, see Split() / string.Join().
If you find any errors or copyright issues, please contact us.