在C#控制台应用程序中居中文本仅使用某些输入

Fre*_*sen 6 c# console-application centering c#-4.0

我在C#.NET4控制台应用程序中居中文本时遇到问题.

这是我将文本居中的方法:

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

但是,我只是输出正常输出的输出.但是,如果我使用此行:

Console.WriteLine(String.Format("{0,"+winWidth+"}", "text"));
Run Code Online (Sandbox Code Playgroud)

"文本"应该居中.

centerText用这两种方法打电话:

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

Rom*_*kov 14

试试这个:

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

初始代码的问题是您的文本在屏幕中心开始.你希望文本的中心在那里.

如果你想打印像这样居中的整个段落,你会做更多的工作.