控制台C#中的居中文本

本文关键字:中文 文本 控制台 | 更新日期: 2023-09-27 18:25:50

当前我正在使用此方法将文本集中在控制台中。

string x = "Whatever I want to print goes here";
Console.SetCursorPosition((Console.WindowWidth - InvalidNo.Length) / 2, Console.CursorTop);
Console.WriteLine(x);

然而,我现在需要集中一些看起来像这样的东西:

players[PlayerNo].Name + " has stolen a piece of cheese from " + players[choice - 1].Name

和类似的东西

"Player {0}", playernum + 1

有没有办法用我的方法做到这一点,或者我必须使用不同的方法?

提前谢谢。

控制台C#中的居中文本

您可以用您的方法做到这一点,只需首先创建字符串,这样您就可以知道它的长度:

string x = players[PlayerNo].Name + " has stolen a piece of cheese from " + players[choice - 1].Name;

然后你就可以使用剩下的代码了。

对于第二个示例,它使用了WriteLine方法的重载,该方法采用格式字符串,因此您将使用String.Format方法来创建字符串:

string x = String.Format("Player {0}", playernum + 1);