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?
The padding-left CSS property sets the width of the padding area to the left of an element.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With