String Formatting in C# to add padding


With C#, you can easily format content and add padding to it.

To add padding −

const string format = "{0,-5} {1,5}";

Now, add the padding to the strings −

string str1 = string.Format(format, "Rank","Student");
string str2 = string.Format(format, "2","Tom");

Let us see the complete code −

Example

 Live Demo

using System;
using System.Collections.Generic;

public class Program {
   public static void Main() {

      // set padding
      const string format = "{0,-5} {1,5}";
      string str1 = string.Format(format, "Rank","Student");
      string str2 = string.Format(format, "2","Tom");

      Console.WriteLine(str1);
      Console.WriteLine(str2);
   }
}

Output

Rank Student
2 Tom

Updated on: 22-Jun-2020

711 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements