Skip to content

PadLeft to Indent and Center Text (C# Console)

Indent, prepend characters, and center text.

String.PadLeft can be used in two ways. The first returns a new string padded with spaces, and the second returns a new string padded with a character.

  • PadLeft(Int32): new string returned padded with spaces. Pass in an integer (the length of string plus the number of spaces to prepend).
  • PadLeft(Int32, Char): new string returned padded with a Unicode character. Pass in an integer (the length of string plus the characters to prepend), and a Unicode character.

Using PadLeft to Indent Text

Text in the console window can be indented with PadLeft. Determine the length of the text string with the Length property, then add the number of spaces to prepend.

string message = "Text to write out";

Console.WriteLine(message.PadLeft(message.Length + 5));

ex
Example of PadLeft

Custom Method

If you'll need an indent more once, you can create a custom method:

static void indent(string message)
{
        Console.WriteLine(message.PadLeft(message.Length + 5));
}

Usage example:

indent("This is an example of prepended text");
ex
Example of a custom function

Using PadLeft to Prepend Characters

You can use the second form of PadLeft to prepend a Unicode character.

Example with bullets
Example with bullets
Console.OutputEncoding = System.Text.Encoding.UTF8;
Console.WriteLine("Grocery List:");
bullet("apples");
bullet("oranges");
bullet("pretzels");

static void bullet(string message)
{
        Console.WriteLine(message.PadLeft(message.Length + 1, '\u2022'));
}

Using PadLeft to Center Text

Center Text: example screenshot
Center text with PadLeft
center("Fancy centered text");

static void center(string message)
{
	int screenWidth = Console.WindowWidth;
	int stringWidth = message.Length;
	int spaces = (screenWidth / 2) + (stringWidth / 2);

	Console.WriteLine("Centering text:");
	Console.WriteLine("Console window width is " + screenWidth + " and the text length is " + stringWidth + ".");
	Console.WriteLine("Divide the screen width by 2 (" + screenWidth / 2 + ").");
	Console.WriteLine("Divide string length by 2 (" + stringWidth / 2 + ") and add those together.");
	Console.WriteLine("The result is the number of spaces needed (" + spaces + ").");

	Console.WriteLine("\n");
	Console.WriteLine("\n");

	Console.WriteLine(message.PadLeft(spaces));
}

For more information read about String.PadLeft at MSDN.