C# Tutorial C# Advanced C# References

C# String - PadLeft() Method



The C# PadLeft() method returns a new string that right-aligns the characters of the given string by padding them with spaces or Unicode character on the left, for a specified total length. However, if the parameter totalWidth is specified less than the number of characters in the string, the method returns the reference of the existing instance. If the totalWidth is equal to the number of characters in the string, the method returns a new string identical to the instance.

Note: This method can be overloaded by passing different type of arguments to it.

Syntax

public string PadLeft (int totalWidth);
public string PadLeft (int totalWidth, char paddingChar);

Parameters

totalWidth Specify the number of characters in the final string equal to the number of characters in the original string plus number of padding characters.
culture Specify a Unicode padding character.

Return Value

Returns the padded version of the string.

Exception

Throws ArgumentOutOfRangeException, if the totalWidth is less than zero.

Example:

In the example below, PadLeft() method returns the padded version of the string called MyStr.

using System;

class MyProgram {
  static void Main(string[] args) {
    string MyStr = "Hello World";

    Console.WriteLine(MyStr.PadLeft(20));
    Console.WriteLine(MyStr.PadLeft(20, '#')); 

    Console.WriteLine(); 
    Console.WriteLine(MyStr.PadLeft(5));
    Console.WriteLine(MyStr.PadLeft(5, '#')); 
  }
}

The output of the above code will be:

         Hello World
#########Hello World

Hello World
Hello World

❮ C# String Methods