c# - 控制台输出的自定义格式

标签 c# string console format alignment

所以我正在尝试编写一个库,以便在控制台中进行一些简单的格式化,这样我就不必在每次创建项目时都这样做。其中包括我想创建一个方法,将您输入的字符串放入一个框中。

这是我的代码:

 public static void DrawBox(string message, char borderChar, ConsoleColor messageColor, ConsoleColor borderColor, int padTop, int padBottom)
     {

        for (int i = 0; i < Console.WindowWidth; i++)
        {
            Console.ForegroundColor = borderColor;
            Console.Write(borderChar);
        }
        for (int i = 0; i < padTop; i++)
        {
            Console.Write(string.Format("{0,0}" + "{0," + (Console.WindowWidth - 1) + "}",borderChar));
        }

        Console.ForegroundColor = borderColor;
        Console.Write(string.Format("{0,0}", borderChar));

        Console.ForegroundColor = messageColor;
        Console.Write("{0," + ((Console.WindowWidth / 2) + message.Length / 2) + "}", message);

        Console.ForegroundColor = borderColor;
        Console.Write("{0," + (((Console.WindowWidth / 5) + message.Length / 5)) + "}", borderChar);

        for (int i = 0; i < padBottom; i++)
        {
            Console.WriteLine(string.Format("{0,0}" + "{0," + (Console.WindowWidth - 1) + "}", borderChar));
        }

        for (int i = 0; i < Console.WindowWidth; i++)
        {
            Console.ForegroundColor = borderColor;
            Console.Write(borderChar);
        }
    }

这行得通,但如果你输入一个更大的字符串,它就会出错。 我该怎么做才能使字符串的格式像这样 无论消息有多大。

*            hi             *
*          world            *

最佳答案

用这些替换中间的 6 行应该可以解决问题

Console.ForegroundColor = borderColor;
Console.Write("{0,-" + (Console.WindowWidth - message.Length) / 2 + "}", borderChar);

Console.ForegroundColor = messageColor;
Console.Write(message);

Console.ForegroundColor = borderColor;
Console.Write("{0," + ((Console.WindowWidth - message.Length) / 2 + message.Length % 2) + "}", borderChar);

关于c# - 控制台输出的自定义格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22831107/

相关文章:

string - 如何检查环境变量是否已设置?

string - 查找其他字母之间的单词 Python

c# - 当我在文本框中键入 RowFilter 时出现语法错误

c# - C# 引用类型在方法内存活多久?

c# - 如何用派生类序列化基类

c# - 快速读取控制台输入

java - Java 控制台应用程序中使用 Windows "cls"命令清屏

c# - 使用 JSON.NET 库覆盖 WriteJson

c++ - 为什么关系运算符在 STL 字符串中重载为非成员函数?

C#:如何将 unicode 字符串打印到控制台?