How do I center text in a console application? [duplicate]

人盡茶涼 提交于 2020-01-22 16:35:10

问题


I am creating a console application and I need to center the text. Is there an easy way to do that, or do I have to place spaces before the text until it is centered? Thank you for your help.

Example, using '|' as the center of the console: Hello|World


回答1:


string s = "Hello|World";
Console.SetCursorPosition((Console.WindowWidth - s.Length) / 2, Console.CursorTop);
Console.WriteLine(s);



回答2:


First get the center of your console by dividing the Console.WindowWidth property by 2. Then you can take it a step further to be more precise; get the length of your string and divide that by 2. Add both of these numbers together and it will center perfect.

    string textToEnter = "44444444444444444444444444444444444444444444";
    Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (textToEnter.Length / 2)) + "}", textToEnter));
    Console.Read();

If your not too familiar with the use of String.Format(), take a look at this:

http://www.dotnetperls.com/string-format



来源:https://stackoverflow.com/questions/21917203/how-do-i-center-text-in-a-console-application

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!