You need to do what is called padding . This until already exists in .NET but only on the left and the right, you need to do this in both, so the ideal would be to create an extension method for this.
using System;
using static System.Console;
public class Program {
public static void Main() {
Write($"|{("Hello World".PadBoth(42))}|");
}
}
namespace System {
public static class StringExt {
public static string PadBoth(this string str, int length, char character = ' ') => str.PadLeft((length - str.Length) / 2 + str.Length, character).PadRight(length, character);
}
}
See running on .NET Fiddle . And no Coding Ground . Also I placed GitHub for future reference .
Particularly I prefer to do this. But if you're sure you can not use this again then nothing prevents you from using inline instead of creating a method.
The extension method you can put into a library with a collection of them and use in all your applications.
Solution based on in this OS response .