问题
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