In daily development, you can always encounter the problem of flow number, similar to yyyy-MM-dd-00001. Many times, while splicing strings, we need to fill in the 0 on the left of "00001". There are two functions in C# that can help you complete this quickly
In C#, PadLeft() is a string method. This method is to supplement the specified character to the length we specified by adding the specified character to the left of the given string, it has two overloaded methods
1>Method (Int32)
2>Method (Int32, Character)
Specific code:
using System; public class MainTest { public static void Main() { string Str = "8"; ((2)); ///Not filling in output ((2, '0')); ///2 byte output, add 0 on the left ((4, '0')); ///4 byte output, add 0 on the left ((4, 'd')); ///4 byte output, left supplement d } }
Output result:
8
08
0008
ddd8
When we do not specify the characters to be filled, the system will use spaces to fill in the number of digits set. When setting a specific character, use specific characters to fill in it.
The usage of PadRight() is similar to PadLeft(), but it is a right-hand filling.
1>Method (Int32)
2>Method (Int32, Character)
using System; public class MainTest { public static void Main() { string Str = "8"; ((2)); ((2, '0')); ((4, '0')); ((4, 'd')); } }
Output result:
8 ---(The horizontal line is added to indicate that there is a space after the number 6)
80
8000
8ddd
Left and right complement are often used when outputting data. We will use these two methods when doing serial communication.
like:
for (int i = 0; i < FRAME_LENTH; i++) { str_ += recive_byte[i].ToString("X").PadLeft(2, '0'); } text_REC.Text = str_ + "\r\n" + text_REC.Text;
This is the end of this article about the detailed explanation of the usage of C# PadLeft and PadRight. For more related C# PadLeft PadRight, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!