C# Reference ยท Strings and Text
C# PadLeft() and PadRight() methods
Reference for C# PadLeft() and PadRight(): pad strings to a fixed width with spaces or any character, align columns, zero-pad numbers, and know the limits.
PadLeft adds characters at the start of a string until it reaches a given total width. PadRight adds them at the end. Both return a new string. If the string is already as wide as requested, or wider, it is returned unchanged: padding never truncates.
Padding is the tool for aligned text columns and for fixed-width fields such as 007 or 0042.
"7".PadLeft(3, '0'); // "007" "ab".PadRight(5, '.'); // "ab..."
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public string PadLeft(int totalWidth) public string PadLeft(int totalWidth, char paddingChar) public string PadRight(int totalWidth) public string PadRight(int totalWidth, char paddingChar)
| Name | Description |
|---|---|
totalWidth |
The number of characters in the resulting string, counting the original. |
paddingChar |
The fill character. The default is a space (' '). |
Returns: a new string of at least totalWidth characters. If the string is already long enough, the same instance is returned.
Errors / undefined behavior: ArgumentOutOfRangeException if totalWidth is negative.
Usage notes
- Width counts UTF-16 chars, not what appears on screen. Emoji, combining marks and East Asian wide characters may look narrower or wider than the number suggests, so columns with such text will not line up. See Iterating characters.
- Numbers.
n.ToString("D5")pads with zeros and handles negative numbers properly;PadLeft(5, '0')on"-7"gives000-7. Use the format string for numbers. See format specifiers. - Alignment in interpolation.
{value,10}right-aligns and{value,-10}left-aligns inside an interpolated string, so you often do not needPad*at all. See String.Format() and interpolation. - Truncating. There is no method that pads and cuts. Combine with
Substringor slicing:s.PadRight(8)[..8]. - Fixed-width files and console tables are the main use. For real tables, compute the maximum width of each column first, then pad to it.
- Allocation. Each call creates a new string. For heavy output,
StringBuilder.Append(char, repeatCount)orstring.Createis cheaper. - Opposite:
Trimremoves characters from the ends.