Skip to content

Instantly share code, notes, and snippets.

@sbrl
Last active January 30, 2018 23:07
Show Gist options
  • Save sbrl/7e0af8818064a858dc6b6d46efc476b6 to your computer and use it in GitHub Desktop.
Save sbrl/7e0af8818064a858dc6b6d46efc476b6 to your computer and use it in GitHub Desktop.
Center pad a string in C♯. #function
namespace System
{
public static class StringExtensions
{
/// <summary>
/// Pads the string on both sides.
/// </summary>
/// <param name="length">The length to pad the string to.</param>
public static string PadBoth(this string str, int length)
{
int spaces = length - str.Length;
int padLeft = spaces / 2 + str.Length;
return str.PadLeft(padLeft).PadRight(length);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment