在C#控制台应用程序中居中文本只处理一些输入 [英] Centering text in C# console app only working with some input

查看:240
本文介绍了在C#控制台应用程序中居中文本只处理一些输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用C#.NET4控制台应用程式时发生文件对中的问题。

I am having a problem with centering text in a C#.NET4 console app.

这是我用来居中文字的方法:

This is my method for centering the text:

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

但是,我只是得到输出,因为它会正常输出。
如果我使用这行:

However, I just get the output as it would have been outputted normally. If I however use this line:

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

文本按其应该居中。

我使用这两种方法调用 centerText

I am calling centerText with these two methods:

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


推荐答案

p>

Try this instead:

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

您的初始代码的问题是您的文本 em>在屏幕中心。

The problem with your initial code was that your text starts in the screen center. You want the center of the text to be there.

如果你想以这样的方式打印整个段落,你将会做更多的工作。

You're going to do a bit more work if you want to print entire paragraphs centered like this.

这篇关于在C#控制台应用程序中居中文本只处理一些输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆