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();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With