string.PadLeft() / PadRight()
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
using System;
// Use PadLeft() to right-align numbers (align digits in a column).
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
// Use PadRight() to left-align text.
string[] items = { "apple", "banana", "cherry" };
int[] prices = { 150, 80, 300 };
for (int i = 0; i < items.Length; i++)
{
Console.WriteLine(items[i].PadRight(8) + prices[i] + " yen");
}
// Use string.Format() to build a formatted string.
string message = string.Format("{0}'s score is {1} points.", "Tanaka", 95);
Console.WriteLine(message); // Tanaka's score is 95 points.
// You can also format numbers (e.g., two decimal places for a percentage).
double discountRate = 0.1567;
Console.WriteLine(string.Format("Discount rate: {0:P1}", discountRate)); // Discount rate: 15.7%
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.