(C#) Indent String(Text) with Spaces

How to indent text with repeated spaces

This example shows how to indent strings using method for padding in C#. To repeat spaces use method String.PadLeft. If you call "test".PadLeft(10) you will get the string aligned to the right: "     test". If you use empty string instead of the "test" string the result will be 10× repeated space character. This can be used to create simple Indent method.

Method to generate Indent:

Code:
public static string Indent(int count)
{
    return "".PadLeft(count);
}


Example:
Console.WriteLine(Indent(0) + "Main Menu");
Console.WriteLine(Indent(3) + "Sub Menu 1");
Console.WriteLine(Indent(6) + "Sub Menu 1.1");
Console.WriteLine(Indent(6) + "Sub Menu 1.2");
Console.WriteLine(Indent(3) + "Sub Menu 2");
Console.WriteLine(Indent(6) + "Sub Menu 2.1");

Output string:
Main Menu
   Sub Menu 1
      Sub Menu 1.1
      Sub Menu 1.2
   Sub Menu 2
      Sub Menu 2.1

If you feel this is helpful or you like it, Please share this using share buttons available on page.

Comments

Popular posts from this blog

Auto Scroll in Common Controls

Convert typed library (.tlb) to .net assembly?

Disable close button on form - C#