Preface
During the programming journey, you often encounter situations where you need to fill the left 0 of the number string. For example, the order number D202411190001, the neat and unified format not only makes people shine, but also helps the boss quickly understand how many orders sold on that day.
This formatting requirement is quite common in actual development. In C#, there are mainly 6 ways to achieve the left filling of numeric strings 0. Let’s take a look!
1、
PadLeft
The method is a simple and straightforward way to fill the specified characters on the left side of the string until the total length is reached.
string number = "42"; string paddedNumber = (5, '0'); // The result is "00042"
2、
()
The method allows us to format the numbers so that they are filled with 0 on the left, maintaining a neat look.
int number = 42; string paddedNumber = ("{0:D5}", number); // The result is "00042"
3. Interpolate string
If you are using C# 6.0 or later, interpolated strings are a more concise way of writing, with functions and()
similar.
int number = 42; string paddedNumber = $"{number:D5}"; // The result is "00042"
4、ToString
You can also use it directlyToString()
Complete the method and format string.
int number = 42; string paddedNumber = ("D5"); // The result is "00042"
5、StringBuilder
StringBuilder
Classes provide an efficient way to build strings that can be used to add a specified number of characters to the left of a string. This method is especially suitable for scenarios where strings need to be constructed efficiently
Example
string number = "123"; int totalLength = 8; char paddingChar = '0'; StringBuilder sb = new StringBuilder(); int paddingLength = totalLength - ; for (int i = 0; i < paddingLength; i++) { (paddingChar); } (number); string paddedNumber = (); (paddedNumber); // Output: 00000123
6、LINQ
If you want to deal with an array of strings, using the LINQ method is a very good choice
string[] numbers = { "1", "23", "456" }; string[] paddedNumbers = (n => (5, '0')).ToArray(); // Output: ["00001", "00023", "00456"]
Summarize
All of the above methods can effectively realize the left complement of the numeric string 0:
PadLeft: Simple and easy to use, suitable for most situations
Format, interpolation and ToString: Flexible and diverse, suitable for strings of various numeric types
StringBuilder: Suitable for scenarios where strings need to be constructed efficiently
LINQ: Suitable for programmers who like functional programming style
Of course, for more complex needs, you can also customize your own way of filling in. I hope these methods can help you become more handy in daily development!
at last
This is the article about six ways and techniques for C# to achieve left zero zero in C#. For more related content on C#’s digital string, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!