Frederik Nielsen Frederik Nielsen - 1 month ago 13
C# Question

Centering text in C# console app only working with some input

I am having a problem with centering text in a C#.NET4 console app.

This is my method for centering the text:

private static void centerText(String text)
{
int winWidth = (Console.WindowWidth / 2);
Console.WriteLine(String.Format("{0,"+winWidth+"}", text));
}


However, I just get the output as it would have been outputted normally.
If I however use this line:

Console.WriteLine(String.Format("{0,"+winWidth+"}", "text"));


The "text" gets centered as it should.

I am calling
centerText
with these two methods:

private static void drawStars()
{
centerText("*********************************************");
}
private static void title(string location)
{
drawStars();
centerText("+++ Du er nu her: " + location + "! +++");
drawStars();
}

Answer

Try this instead:

private static void centerText(String text)
{
    Console.Write(new string(' ', (Console.WindowWidth - text.Length) / 2));
    Console.WriteLine(text);
}

The problem with your initial code was that your text starts in the screen center. You want the center of the text to be there.

You're going to do a bit more work if you want to print entire paragraphs centered like this.