From 233d31a4b435d7b7c6be71deaa870b07ba6d709f Mon Sep 17 00:00:00 2001 From: BitMap7487 <84928779+BitMap7487@users.noreply.github.com> Date: Mon, 6 Jan 2025 23:42:11 +0100 Subject: [PATCH] Create centered-console-text.md Code snippet for displaying centered text in a console application. --- .../string-utilities/centered-console-text.md | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 snippets/csharp/string-utilities/centered-console-text.md diff --git a/snippets/csharp/string-utilities/centered-console-text.md b/snippets/csharp/string-utilities/centered-console-text.md new file mode 100644 index 00000000..e71c4757 --- /dev/null +++ b/snippets/csharp/string-utilities/centered-console-text.md @@ -0,0 +1,42 @@ +--- +title: Centered Console Text +description: Output console text centered in the window. +author: BitMap7487 +tags: console, csharp, string-formatting, text-alignment +--- + +```csharp +static void CenteredOutput(object input) +{ + if (input is IEnumerable enumerable && !(input is string)) + { + foreach (var message in enumerable) + { + PrintCentered(message.ToString()); + } + } + else + { + PrintCentered(input.ToString()); + } +} + +private static void PrintCentered(string str) +{ + int centerPosition = Console.WindowWidth / 2 + str.Length / 2; + Console.WriteLine(string.Format("{0," + centerPosition + "}", str)); +} + +// Usage: +List messages = new List() +{ + "Hello world!", + "This is a test" +}; + +string[] messageArray = { "Array test 1", "Array test 2" }; + +CenteredOutput(messages); +CenteredOutput(messageArray); +CenteredOutput("Single string test"); +```