McDonnellDean McDonnellDean - 2 months ago 26
C# Question

Pad Left & Pad Right (Pad Center) String

String has both

. 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?


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.