McDonnellDean McDonnellDean - 4 months ago 54
C# Question

Pad Left & Pad Right (Pad Center) String

String has both

PadLeft
and
PadRight
. I am in need of padding both left and right (center justification). Is there a standardized way of doing this, or better yet, a built in way of achieving the same goal?

Answer

Not that I know of. You can create an extension method if you see yourself using it a lot. Assuming you want your string to end up in the center, use something like the following

public string PadBoth(string source, int length)
{
    int spaces = length - source.Length;
    int padLeft = spaces/2 + source.Length;
    return source.PadLeft(padLeft).PadRight(length);

}

To make this an extension method, do it like so:

namespace System
{
    public static class StringExtensions
    {
        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);
        }
    }
}

As an aside, I just include my extensions in the system namespace - it's up to you what you do.