【问题标题】:Centering text in C# console app only working with some input在 C# 控制台应用程序中居中文本仅适用于某些输入
【发布时间】:2012-10-02 14:43:24
【问题描述】:

我在 C#.NET4 控制台应用程序中将文本居中时遇到问题。

这是我将文本居中的方法:

private static void centerText(String text)
{
    int winWidth = (Console.WindowWidth / 2);
    Console.WriteLine(String.Format("{0,"+winWidth+"}", text));
}

但是,我只是得到了正常输出的输出。 但是,如果我使用这一行:

Console.WriteLine(String.Format("{0,"+winWidth+"}", "text"));

“文本”应该居中。

我用这两种方法打电话给centerText

private static void drawStars()
{
    centerText("*********************************************");
}
private static void title(string location)
{
    drawStars();
    centerText("+++ Du er nu her: " + location + "! +++");
    drawStars();
}

【问题讨论】:

  • 当/因为您的文本长度超过屏幕宽度的一半时会出现问题。
  • @DaveShaw 还有一个比这更大的问题:文本宽度从来都不是居中的一部分。

标签: c# c#-4.0 console-application centering


【解决方案1】:

试试这个:

private static void centerText(String text)
{
    Console.Write(new string(' ', (Console.WindowWidth - text.Length) / 2));
    Console.WriteLine(text);
}

您的初始代码的问题是您的文本开始 在屏幕中心。您希望文本的中心在那里。

如果你想打印这样居中的整个段落,你需要做更多的工作。

【讨论】:

    【解决方案2】:

    我有自己的调用控制台头的方法:

    public static void Header(string title, string subtitle = "", ConsoleColor color = ConsoleColor.White)
    {
        int windowWidth = 90 - 2;
        string titleContent = String.Format("║{0," + ((windowWidth / 2) + (title.Length / 2)) + "}{1," + (windowWidth - (windowWidth / 2) - (title.Length / 2) + 1) + "}", title, "║");
        string subtitleContent = String.Format("║{0," + ((windowWidth / 2) + (subtitle.Length / 2)) + "}{1," + (windowWidth - (windowWidth / 2) - (subtitle.Length / 2) + 1) + "}", subtitle, "║");
    
        Console.WriteLine("╔════════════════════════════════════════════════════════════════════════════════════════╗");
        Console.WriteLine(titleContent);
        if (!string.IsNullOrEmpty(subtitle))
        {
            Console.WriteLine(subtitleContent);
        }
        Console.WriteLine("╚════════════════════════════════════════════════════════════════════════════════════════╝");
    }
    

    那你这样称呼YourStaticClass.Header("Test", "Version 1.0");

    应该是这样的:

    ╔════════════════════════════════════════════════════════════════════════════════════════╗
    ║                                          Test                                          ║
    ║                                      Version 1.0                                       ║
    ╚════════════════════════════════════════════════════════════════════════════════════════╝
    

    您可以将windowsWidth 中的90 替换为Console.WindowWidth

    更新 - 2019 年 2 月 - 代码清理并动态大小

    /// <summary>
    /// Application header, also sets the console title
    /// </summary>
    /// <param name="title">Title of application</param>
    /// <param name="subtitle">Subtitle of application</param>
    /// <param name="foreGroundColor">Foreground color</param>
    public static void Header(string title, string subtitle = "", ConsoleColor foreGroundColor = ConsoleColor.White, int windowWidthSize = 90)
    {
        Console.Title = title + (subtitle != "" ? " - " + subtitle : "");
        string titleContent = CenterText(title, "║");
        string subtitleContent = CenterText(subtitle, "║");
        string borderLine = new String('═', windowWidthSize - 2);
    
        Console.ForegroundColor = foreGroundColor;
        Console.WriteLine($"╔{borderLine}╗");
        Console.WriteLine(titleContent);
        if (!string.IsNullOrEmpty(subtitle))
        {
            Console.WriteLine(subtitleContent);
        }
        Console.WriteLine($"╚{borderLine}╝");
        Console.ResetColor();
    }
    
    /// <summary>
    /// Align content to center for console. Can be used with decoration if used inside menu or header
    /// </summary>
    /// <param name="content">Content to center</param>
    /// <param name="decorationString">Left and right decoration, default is empty/none</param>
    /// <returns>Center aligned text</returns>
    public static string CenterText(string content, string decorationString = "", int windowWidthSize = 90)
    {
        int windowWidth = windowWidthSize - (2 * decorationString.Length);
        return String.Format(decorationString + "{0," + ((windowWidth / 2) + (content.Length / 2)) + "}{1," + (windowWidth - (windowWidth / 2) - (content.Length / 2) + decorationString.Length) + "}", content, decorationString);
    }
    

    【讨论】:

    • 虽然这不是公认的答案,但绝对可以添加到我的库中。但我也建议动态生成边框;)+1
    • 不错。这是一个提示,但你还是更新了你的答案。现在其他人更容易找到一个好的解决方案。谢谢:)
    • 只想指出,您没有在相应的 Header 调用中将窗口大小传递给 CenterText。
    • 是的,它的值默认设置为 90:int windowWidthSize = 90
    【解决方案3】:

    传入的文本可能有空格,例如\r\n,然后在调用写入之前将其删除,例如

    string textClean = Regex.Replace(text, @"([\r\n])", string.Empty);
    
    // Then center on text clean 
    

    【讨论】:

    • 虽然这是个好建议,但这似乎不是根本问题。因此,这可能只是一个评论。
    • 是的,它没有回答这个问题,但最好指出来。当你做这样的事情时,你很快就会忘记它。我会用这个:string cleanText = text.Replace(Environment.NewLine, string.Empty);
    猜你喜欢
    • 1970-01-01
    • 2014-10-09
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    相关资源
    最近更新 更多