C#'s `PadLeft()` Method: Adding Leading Padding to Strings for Enhanced Formatting

Learn how to use C#'s `PadLeft()` string method to add padding characters to the left side of a string. This tutorial explains its functionality, demonstrates its use with different padding characters and lengths, and highlights its application in creating formatted output and aligning strings.



Understanding C# `PadLeft()`

The C# `PadLeft()` method is a string manipulation function that adds padding characters to the left side of a string to make it reach a specified length. This is helpful for formatting strings, ensuring they align correctly.

How `PadLeft()` Works

If the string's length is less than the specified `length`, `PadLeft()` adds padding characters to the left until the desired length is reached. If the string is already longer than or equal to the specified length, it's returned unchanged.

`PadLeft()` Method Signatures

The `PadLeft()` method has two versions:

  • public string PadLeft(int length): Adds spaces to the left until the string reaches length characters.
  • public string PadLeft(int length, char paddingChar): Adds the specified character (`paddingChar`) to the left until the string reaches length characters.

Parameters

  • length (int): The desired total length of the string after padding.
  • paddingChar (char, optional): The character used for padding (space is the default).

Return Value

The method returns a new string with the added left padding.

Example


using System;

public class StringExample {
    public static void Main(string[] args) {
        string s1 = "Hello C#"; // Length 8
        string s2 = s1.PadLeft(10); // Adds 2 spaces to the left
        Console.WriteLine(s2); // Output:  Hello C#
    }
}

In this example, "Hello C#" (length 8) is padded with spaces to reach a length of 10.