C# String PadLeft() Method
The PadLeft()
method in C# is used to pad a string with a specified character or set of characters on the left side, so that the resulting string has a specified total length. If the length of the original string is greater than or equal to the specified total length, the method returns the original string without any padding.
The syntax of the PadLeft()
method is as follows:
string.PadLeft(totalWidth);
or
string.PadLeft(totalWidth, paddingChar);
Here, totalWidth
is the total length of the resulting string, including the original string and any padding characters, and paddingChar
is the character to use for padding. If paddingChar
is not specified, the method uses the space character (' ') for padding.
For example, to pad a string with spaces on the left side so that the resulting string has a total length of 10 characters, you can use the following code:
string text = "Hello"; string paddedText = text.PadLeft(10); Console.WriteLine(paddedText); // Output: " Hello"
In this example, the PadLeft()
method is used to pad the string "Hello" with spaces on the left side so that the resulting string has a total length of 10 characters. The resulting string " Hello" is then assigned to the paddedText
variable and printed to the console using the WriteLine()
method.
You can also use the PadLeft()
method to pad a string with a specified character on the left side. For example, to pad a string with zeros on the left side so that the resulting string has a total length of 8 characters, you can use the following code:
string number = "123"; string paddedNumber = number.PadLeft(8, '0'); Console.WriteLine(paddedNumber); // Output: "00000123"
In this example, the PadLeft()
method is used to pad the string "123" with zeros on the left side so that the resulting string has a total length of 8 characters. The resulting string "00000123" is then assigned to the paddedNumber
variable and printed to the console.