Add zero padding to a string in C#
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = "123"; s = s.PadLeft(5, '0'); Console.WriteLine(s); // 00123 } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; public class Example { public static void Main() { string s = "123"; s = s.PadRight(5, '0'); Console.WriteLine(s); // 12300 } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { string s = "123"; int len = 4; s = s.PadRight(len, '0').Substring(0, len); Console.WriteLine(s); // 1230 } } |
That’s all about adding zero padding to a string in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)