I've been trying to figure out a shortcut in putting a long string text positioned in a specific coordinate without using Console.SetCursorPosition
and Console.WriteLine
multiple times. I plan on using the shortcut especially in positioning ASCII text.
I've tried doing Console.SetCursorPosition
then the @
to put the long string text altogether only to discover that only the first line is affected by the Console.SetCursorPosition
.
Console.SetCursorPosition(50, 1);
Console.WriteLine("Hello");
Console.SetCursorPosition(50, 2);
Console.WriteLine("World");
Console.ReadKey();
I expect the output to display Hello
somehow at the middle with World
just below it.
You can write a function to do this. For example:
static void Print(int left, int top, params string[] lines)
{
foreach (string line in lines)
{
Console.SetCursorPosition(left, top);
Console.WriteLine(line);
top++;
}
}
And call it like this:
Print(50, 1, "Hello", "World");
Or equivalently like this:
string[] lines = { "Hello", "World" };
Print(50, 1, lines);
If the text consists of words separated by spaces, and you want to put a single word on each line, then you can split the text at spaces, inside the function. That way you would be able to pass a single line of text.
static void Print(int left, int top, params string[] lines)
{
foreach (string line in lines)
{
string[] words = line.Trim().Split(new char[] { ' ' });
foreach (string word in words)
{
Console.SetCursorPosition(left, top);
Console.WriteLine(word);
top++;
}
}
}
And call it like this:
Print(50, 1, "Hello World");