当前位置: 首页 > 编程语言 > C#

在C#console app中居中文本仅使用某些输入分享

时间:2023-04-10 18:14:08 C#

C#学习教程:仅使用某些输入在C#控制台应用程序中居中文本以下是我如何将文本居中:privatestaticvoidcenterText(Stringtext){intwinWidth=(Console.WindowWidth/2);Console.WriteLine(String.Format("{0,"+winWidth+"}",text));但是,我只是像往常一样得到输出。但是,如果我使用这一行:Console.WriteLine(String.Format("{0,"+winWidth+"}","text"));“文本”应该居中。我用这两种方法调用centerText:privatestaticvoiddrawStars(){centerText("***********************************************”);}privatestaticvoidtitle(stringlocation){drawStars();centerText("+++都儿女:"+location+"!+++");绘制星星();}试试这个:privatestaticvoidcenterText(Stringtext){Console.Write(newstring('',(Console.WindowWidth-text.Length)/2));控制台.WriteLine(文本);您的初始代码的问题是您的文本从屏幕中央开始。您希望文本的中心在那里。如果你想像这样居中打印整个段落,你会做更多的工作。传入的文本可能有像rn这样的空格,然后在调用write之前将其删除,如stringtextClean=Regex.Replace(text,@"([rn])",string.Empty);//Thencenterontextclean我有自己的方法来调用控制台标头:publicstaticvoidHeader(stringtitle,stringsubtitle="",ConsoleColorcolor=ConsoleColor.White){intwindowWidth=90-2;stringtitleContent=String.Format("║{0,"+((windowWidth/2)+(title.Length/2))+"}{1,"+(windowWidth-(windowWidth/2)-(title.Length/2)+1)+"}",标题,"║");stringsubtitleContent=String.Format("║{0,"+((windowWidth/2)+(subtitle.Length/2))+"}{1,"+(windowWidth-(windowWidth/2)-(subtitle.Length/2)+1)+"}",副标题,"║");Console.WriteLine("╔════════════════凄凉══════════════════");Console.WriteLine(titleContent);if(!string.IsNullOrEmpty(subtitle)){Console.WriteContent(subtitle);}Console.WriteLine("╚═════════════════════════════════════════════════════════════════════════════════════╝");}然后你就叫它YourStaticClass.Header("Test","Version1.0");应该是这样的:╔═════凄凉║测试║║版本1.0║╚════════惨淡══════════════════════════════consoleapp中仅使用部分输入,分享所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注,本文收集自网络,不代表正文位置,如涉及侵权,请点击右侧联系管理员删除,如需转载请注明出处: