Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 275
Frederik Nielsen Avatar asked Oct 11 '12 20:10

Frederik Nielsen


1 Answers

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.

like image 53
Roman Starkov Avatar answered Sep 18 '22 23:09

Roman Starkov