C# | Left padding a string with spaces

In this tutorial, we will learn how to left pad a string with spaces in C#? By IncludeHelp Last updated : April 09, 2023

How to left pad a string with spaces in C#?

The string.PadLeft() method is used to pad left a string with spaces.

Syntax

string string.PadLeft(int totalWidth);

Here, totalWidth is the total number of characters of the string, if it is more than the length of the string, string will be padded with spaces, method returns the space padded string.

C# program to pad left a string with spaces

using System;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {

      string str = "Hello world";

      Console.WriteLine("Demonstration of PadLeft method");
      Console.WriteLine(str.PadLeft(str.Length + 1));
      Console.WriteLine(str.PadLeft(str.Length + 2));
      Console.WriteLine(str.PadLeft(str.Length + 3));
      Console.WriteLine(str.PadLeft(str.Length + 4));
      Console.WriteLine(str.PadLeft(str.Length + 5));

      Console.WriteLine();
    }
  }
}

Output

Demonstration of PadLeft method
 Hello world
  Hello world
   Hello world
    Hello world
     Hello world



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.