(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
Post a Comment