首页 > 解决方案 > 在控制台中心粘贴 Ascii Art

问题描述

嗨,我试图将 ascii 艺术粘贴到 C# 中的屏幕中心,它将普通文本打印到屏幕中心,但不是 ascii 艺术,有什么想法吗?(对不起,我是 C# 新手)

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string textToEnter = @"



 /$$$$$$$$ /$$$$$$$$  /$$$$$$  /$$$$$$$$
|__  $$__/| $$_____/ /$$__  $$|__  $$__/
   | $$   | $$      | $$  \__/   | $$   
   | $$   | $$$$$   |  $$$$$$    | $$   
   | $$   | $$__/    \____  $$   | $$   
   | $$   | $$       /$$  \ $$   | $$   
   | $$   | $$$$$$$$|  $$$$$$/   | $$   
   |__/   |________/ \______/    |__/   
                                        
                                        
                                        
                                       
                                                  


                ";
            Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (textToEnter.Length / 2)) + "}", textToEnter));
            Console.Read();
            Console.WriteLine("Hello World!");
        }
    }
}

标签: c#consoleconsole-application

解决方案


将整个文本块作为一个整体而不是每一行居中的一种方法是首先确定最长行的长度,然后确定使该行居中所需的左侧填充,然后将该填充添加到每行的开头的文本块。

我们可以通过分割NewLine字符,填充每一行,然后重新加入修改后的行来做到这一点:

var lines = textToEnter.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
var longestLength = lines.Max(line => line.Length);
var leadingSpaces = new string(' ', (Console.WindowWidth - longestLength) / 2);
var centeredText = string.Join(Environment.NewLine, 
    lines.Select(line => leadingSpaces + line));

Console.WriteLine(centeredText);

推荐阅读