在C#console app中居中文本仅使用某些输入
我在C#.NET4控制台应用程序中居中文本时遇到问题。
这是我将文本居中的方法:
private static void centerText(String text) { int winWidth = (Console.WindowWidth / 2); Console.WriteLine(String.Format("{0,"+winWidth+"}", text)); }
但是,我只是得到输出,因为它会正常输出。 但是,如果我使用此行:
Console.WriteLine(String.Format("{0,"+winWidth+"}", "text"));
“文本”按照应有的方式居中。
我用这两种方法调用centerText
:
private static void drawStars() { centerText("*********************************************"); } private static void title(string location) { drawStars(); centerText("+++ Du er nu her: " + location + "! +++"); drawStars(); }
试试这个:
private static void centerText(String text) { Console.Write(new string(' ', (Console.WindowWidth - text.Length) / 2)); Console.WriteLine(text); }
初始代码的问题是您的文本在屏幕中心开始 。 你想要文本的中心在那里。
如果你想打印像这样居中的整个段落,你会做更多的工作。
传入的文本可能有空格,如\r\n
,然后在调用写入之前删除它,如
string textClean = Regex.Replace(text, @"([\r\n])", string.Empty); // Then center on text clean
我有自己的方法来调用控制台标头:
public static void Header(string title, string subtitle = "", ConsoleColor color = ConsoleColor.White) { int windowWidth = 90 - 2; string titleContent = String.Format("║{0," + ((windowWidth / 2) + (title.Length / 2)) + "}{1," + (windowWidth - (windowWidth / 2) - (title.Length / 2) + 1) + "}", title, "║"); string subtitleContent = String.Format("║{0," + ((windowWidth / 2) + (subtitle.Length / 2)) + "}{1," + (windowWidth - (windowWidth / 2) - (subtitle.Length / 2) + 1) + "}", subtitle, "║"); Console.WriteLine("╔════════════════════════════════════════════════════════════════════════════════════════╗"); Console.WriteLine(titleContent); if (!string.IsNullOrEmpty(subtitle)) { Console.WriteLine(subtitleContent); } Console.WriteLine("╚════════════════════════════════════════════════════════════════════════════════════════╝"); }
然后你将它称为YourStaticClass.Header("Test", "Version 1.0");
它应该是这样的:
╔════════════════════════════════════════════════════════════════════════════════════════╗ ║ Test ║ ║ Version 1.0 ║ ╚════════════════════════════════════════════════════════════════════════════════════════╝
您可以使用Console.WindowWidth
替换windowsWidth
的90