c# - 在控制台中心粘贴 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!");
}
}
}
解决方案
将整个文本块作为一个整体而不是每一行居中的一种方法是首先确定最长行的长度,然后确定使该行居中所需的左侧填充,然后将该填充添加到每行的开头的文本块。
我们可以通过分割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);
推荐阅读
- python - 在 django bulk_create 中获取 IntegrityError 的键
- javascript - 基于 Angular/ChartJS 中的 API 动态更新图形(移动线图)
- javascript - 使用 webpack 在 Django 服务器上运行 React App 的问题
- python - 防止通过 Ctrl+D 关闭 python IDLE shell
- sql - 当表 B 上没有运行查询时如何将数据从表 A 切换到表 B
- python - 如何根据唯一列组合 Pandas 数据框
- javascript - JavaScript - 如何在显示为正方形/矩阵的元素的线性数组中按键查找元素的 x,y 位置?
- python - 将数据帧的部分行从数字转换为日期时间,但得到奇怪的数字
- android - 从一部手机到另一部手机的远距离Android屏幕共享
- java - 即使导入了类也找不到符号