String Formatting in C# to add padding

CsharpProgrammingServer Side Programming

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
raja
Published on 31-Aug-2018 16:44:00
Advertisements