【问题标题】:How to display multiple line string in the center of the console如何在控制台中心显示多行字符串
【发布时间】:2021-12-22 17:24:57
【问题描述】:

我正在控制台中编写一个 C# 游戏,其中对象具有保存其模型的字符串类型成员,例如:

string model = "####\n####\n####\n####";

我想将它们放在不同的地方,但是当我使用Console.SetCursorPosition()Console.Write(model) 时,第一行显示我设置位置的位置,但下一行写在新行的开头,输出如下所示:

          ####
####
####
####

我尝试使用 @ 前缀,但它不起作用。有没有办法将此字符串显示为控制台中间的正方形?

【问题讨论】:

  • 您显然可以猜到它发生的原因。因此,您将需要重新考虑您的问题。一种低技术的方法可能是拆分添加空格,然后重新加入string.Join(Environment.NewLine,model.Split('\n').Select(x => $"{new string(' ',<Count>}{x}")); 另一种方法是放弃在一个写入语句中全部写入,并将拆分字符串迭代到正确的控制台坐标

标签: c#


【解决方案1】:

在字符串中使用 \t:

string model = "\t\t\t####\n\t\t\t####\n\t\t\t####\n\t\t\t####";

输出是:

        ####
        ####
        ####
        ####

【讨论】:

    【解决方案2】:

    请看this thread
    根据 Roman Starkov 的回答,应该能够在一行中实现您所需要的。
    对于多行,试试这个:

    static void CenterText(string text)
    {
        Console.Write(new string(' ', (Console.WindowWidth - text.Length) / 2));
        Console.WriteLine(text);
    }
    
    static void Main(string[] args)
    {
        string model = "####\n####\n####\n####";
        foreach (var m in model.split("\n"))
        {
            CenterText(m);
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以编写一个小实用程序方法,根据'\n' 拆分字符串并为每个块应用SetCursorPosition

      例如,

      static void WriteInCenter(string data)
      {
        foreach (var model in data.Split('\n'))
        {
          Console.SetCursorPosition((Console.WindowWidth - model.Length) / 2, Console.CursorTop);
          Console.WriteLine(model);
        }
      }
      

      您现在可以调用该方法

      string model = "####\n####\n####\n####";
      WriteInCenter(model);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-03
        • 2015-10-25
        • 2021-01-13
        • 2020-10-14
        • 2012-09-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多