Reputation: 1
hi im trying to paste ascii art and make it into the center of the screen in C#, it prints normal text to the center of the screen but not ascii art, any ideas? (sorry im new to 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!");
}
}
}
Upvotes: 0
Views: 2385
Reputation: 37020
One way to center the entire block of text as a whole rather than each individual line is to first determine the length of the longest line, then determine the left padding required to center that line, and then add that padding to the beginning of each line of the block of text.
We can do this by splitting on the NewLine
character, padding each line, and then rejoining the modified lines again:
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);
Upvotes: 1
Reputation: 13
Probably this code snippet could help you to solve your issue:
using (StringReader reader = new StringReader(textToEnter))
{
string line = string.Empty;
do
{
line = reader.ReadLine();
if (line != null)
{
Console.SetCursorPosition((Console.WindowWidth - line.Length) / 2, Console.CursorTop);
Console.WriteLine(line);
}
} while (line != null);
}
The code is used to read the string line by line, and before printing it to the terminal, instead of formatting the string by adding white space before the text, we can just move the cursor where we need to print.
Upvotes: 0