The PadLeft()
method in C# is used to pad a string with a specified character or whitespace on the left side to achieve a desired total length.
The syntax of the PadLeft()
method is as follows:
public string PadLeft(int totalWidth) public string PadLeft(int totalWidth, char paddingChar)
The first overload of PadLeft()
takes the totalWidth
parameter, which represents the total desired length of the resulting string. It pads the original string with spaces on the left side to reach the specified length. If the original string is already equal to or longer than the totalWidth
, the method returns the original string without any modifications.
Here’s an example:
string originalString = "Hello"; string paddedString = originalString.PadLeft(10); Console.WriteLine(paddedString); // Output: " Hello"
In the above example, the original string “Hello” is padded with five spaces on the left side to reach a total length of 10.
The second overload of PadLeft()
takes an additional paddingChar
parameter, which represents the character to be used for padding instead of spaces.
Here’s an example using the second overload:
string originalString = "Hello"; string paddedString = originalString.PadLeft(10, '*'); Console.WriteLine(paddedString); // Output: "*****Hello"
In this case, the original string “Hello” is padded with five asterisks (*) on the left side to reach a total length of 10.
Both overloads of PadLeft()
return a new string with the padding applied, leaving the original string unchanged.
C# String PadLeft() Method Example:
Certainly! Here’s an example that demonstrates the usage of the PadLeft()
method in C#:
using System; class Program { static void Main() { string originalString = "123"; int totalWidth = 8; char paddingChar = '0'; string paddedString = originalString.PadLeft(totalWidth, paddingChar); Console.WriteLine("Original String: " + originalString); Console.WriteLine("Padded String: " + paddedString); } }
Output:
Original String: 123 Padded String: 00000123
In this example, the originalString
is “123”. We want to pad it on the left side with zeros (0
) to achieve a total width of 8 characters. The PadLeft()
method is called with the totalWidth
parameter set to 8 and the paddingChar
parameter set to ‘0’. As a result, the paddedString
becomes “00000123” with five zeros added on the left side to reach the desired total width.
Note that if the original string is already equal to or longer than the totalWidth
, no padding is applied, and the original string remains unchanged.