Indent String with Spaces

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

The Indent method:

public static string Indent(int count)

{

    return "".PadLeft(count);

}

 

Test code:

Console.WriteLine(Indent(0) + "List");

Console.WriteLine(Indent(3) + "Item 1");

Console.WriteLine(Indent(6) + "Item 1.1");

Console.WriteLine(Indent(6) + "Item 1.2");

Console.WriteLine(Indent(3) + "Item 2");

Console.WriteLine(Indent(6) + "Item 2.1");

 

Output string:

List

   Item 1

      Item 1.1

      Item 1.2

   Item 2

      Item 2.1


Mr. Ravi Krishna - Senior Software Engineer
I am a Mocrosoft ASP.net Developer and MCP Certified professional. I have overall 5 years of experience in IT Industry,in that 3 years experience in Microsoft BI(SSAS,SSIS,SSRS). I have experience on various business domains like Automation and Chemical.
https://sites.google.com/site/rkkumardotnet/
Read moreRead more about Contributor