如何将Console.WriteLine与中心对齐

时间:2016-10-26 18:28:27

标签: c#

我尝试对齐文本,所以我有一个金字塔,但我找不到解决方案。

Console.Write("Bitte geben Sie die Anzahl der Zeilen der Pyramide ein: ");
int zeilen = Convert.ToInt32(Console.ReadLine());
string raute = "#";
string stern = "*";
int anzahlzeichen = -1;
double hilfsvariable = 1;

while(zeilen > 0)
{
    anzahlzeichen += 2;
    int x = anzahlzeichen;

    while(x > 0)
    {
        if (hilfsvariable%2 == 0)
        {
            Console.Write("{0}", stern);
            x--;
        }
        else
        {
            Console.Write("{0}", raute);
            x--;
        }
    }

    hilfsvariable += 1;
    Console.WriteLine();
    zeilen--;
}

现在它从左侧开始打印所有内容。

有人知道如何将它与中心对齐吗?

谢谢

1 个答案:

答案 0 :(得分:3)

它会在中心字符串:

string str = "Hello";
Console.SetCursorPosition((Console.WindowWidth - str.Length) / 2, Console.CursorTop);
Console.WriteLine(str);
相关问题