This post will discuss how to add zero padding to a string in C#.

1. Using String.PadLeft() method

The String.PadLeft() construct a string of a specified length from the original string, where the string is left-padded with the specified character. Note that if the length of the original string is more than the specified length, the PadLeft() method won’t truncate the string.

Download  Run Code

2. Using String.PadRight() method

The String.PadRight() construct a string of a specified length from the original string, where the string is right-padded with the specified character.

Download  Run Code

 
Similar to the PadLeft() method, the PadRight() method won’t truncate the string when the length of the string is more than the specified length. To truncate (or pad) a string to a fixed length, invoke the Substring() method on the output of the PadRight() method, as shown below:

Download  Run Code

That’s all about adding zero padding to a string in C#.