Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad Left & Pad Right (Pad Center) String

Tags:

c#

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?

like image 339
McDonnellDean Avatar asked Jul 11 '13 10:07

McDonnellDean


People also ask

What is PAD left?

The padding-left CSS property sets the width of the padding area to the left of an element.

What is PAD in JavaScript?

The padStart() method in JavaScript is used to pad a string with another string until it reaches the given length. The padding is applied from the left end of the string.

What is padding in C#?

In C#, PadLeft() is a string method. This method is used to right-aligns the characters in String by padding them with spaces or specified character on the left, for a specified total length. This method can be overloaded by passing different parameters to it.

What is PadLeft in VB net?

PadLeft method creates a new string by concatenating enough leading pad characters to an original string to achieve a specified total length. The String. PadLeft(Int32) method uses white space as the padding character and the String. PadLeft(Int32, Char) method enables you to specify your own padding character.


1 Answers

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.

like image 183
David Colwell Avatar answered Oct 13 '22 03:10

David Colwell