C# String PadLeft()

The String PadLeft() method returns a new string of a specified length in which the beginning of the current string is padded with spaces or with a specified character.

Example

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Icecream";
     
// returns string with length 9 // padded with one space at left string result = str.PadLeft(9);
Console.WriteLine(result); Console.ReadLine(); } } } // Output: Icecream

PadLeft() Syntax

The syntax of the string PadLeft() method is:

PadLeft(int totalWidth, char paddingChar)

Here, PadLeft() is a method of class String.


PadLeft() Parameters

The PadLeft() method takes the following parameters:

  • totalWidth - number of characters in the resulting string (number of characters in given string plus additional padding characters)
  • paddingChar - padding character

PadLeft() Return Value

The PadLeft() method returns:

  • new string with left padding

Example 1: C# String PadLeft()

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Icecream";
      string result;
     
// returns new string with length 20 // padded with space at left result = str.PadLeft(20);
Console.WriteLine("Result: " + result);
// returns original string result = str.PadLeft(2);
Console.WriteLine("Result: " + result);
// returns new string // identical to given string result = str.PadLeft(8);
Console.WriteLine("Result: " + result); Console.ReadLine(); } } }

Output

Result:         	Icecream
Result: Icecream
Result: Icecream

Here,

  • str.PadRight(20) - returns new string with length 20 padded with spaces at left
  • str.PadRight(2) - returns given string as totalWidth is less than length of the given string
  • str.PadRight(8) - returns new string that is identical to the given string as totalWidth is equal to length of the string

Example 2: C# String PadLeft() With paddingChar

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Icecream";
      char pad = '^';
      string result;
     
// returns string with length 9 // padded with '^' at left result = str.PadLeft(9, pad);
Console.WriteLine("Result: " + result);
// returns original string result = str.PadLeft(2, pad);
Console.WriteLine("Result: " + result);
// returns string with length 20 // padded with '^' at left result = str.PadLeft(20, pad);
Console.WriteLine("Result: " + result); Console.ReadLine(); } } }

Output

Result: ^Icecream
Result: Icecream
Result: ^^^^^^^^^^^^Icecream
Did you find this article helpful?