如何在控制台应用程序中居中文本?

我正在创建一个控制台应用程序,我需要将文本居中。 有没有一种简单的方法可以做到这一点,或者我必须在文本前放置空格直到它居中? 谢谢您的帮助。

例如,使用’|’ 作为控制台的中心:Hello | World

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

首先通过将Console.WindowWidth属性除以2来获得控制台的中心。然后,您可以更进一步,更精确; 得到你的字符串的长度,并将其除以2.将这两个数字加在一起,它将居中完美。

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

在此处输入图像描述

如果您不太熟悉String.Format()的使用,请看一下:

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