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?
8 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.
-
1Modified the last line to use non-breaking spaces (alt+0160),
.PadRight(length, ' ');
. This helps keep the padding showing even if the display environment doesn't like multiple spaces. Nov 5, 2015 at 21:44
Here is a custom implementation, not requiring rebuilding of strings.
Also it works correctly with odd numbers
static string PadCenter(string text, int newWidth)
{
const char filler = ' ';
int length = text.Length;
int charactersToPad = newWidth - length;
if (charactersToPad < 0) throw new ArgumentException("New width must be greater than string length.", "newWidth");
int padLeft = charactersToPad/2 + charactersToPad%2;
//add a space to the left if the string is an odd number
int padRight = charactersToPad/2;
StringBuilder resultBuilder = new StringBuilder(newWidth);
for (int i = 0; i < padLeft; i++) resultBuilder.Insert(i, filler);
for (int i = 0; i < length; i++) resultBuilder.Insert(i + padLeft, text[i]);
for (int i = newWidth - padRight; i < newWidth; i++) resultBuilder.Insert(i, filler);
return resultBuilder.ToString();
}
Here's a slightly improved version of @david-colwell's extension method that also optionally takes a padding character:
namespace System
{
public static class StringExtensions
{
public static string PadSides(this string str, int totalWidth, char paddingChar = ' ')
{
int padding = totalWidth - str.Length;
int padLeft = padding / 2 + str.Length;
return str.PadLeft(padLeft, paddingChar).PadRight(totalWidth, paddingChar);
}
}
}
You could do it yourself with this:
string test = "Wibble";
int padTo = 12;
int padSize = (padTo - test.Length) / 2;
if (padSize > 0) {
test = test.Trim().PadLeft(test.Length + padSize).PadRight(test.Length + 2 * padSize);
}
Just adjust this to deal with odd padding lengths as required and make it an extension method if that makes your life easier.
Here a bit of an improvement I think.
namespace System
{
public static class StringExtensions
{
public static string PadCenter(this string str, int totalLength, char padChar = '\u00A0')
{
int padAmount = totalLength - str.Length;
if (padAmount <= 1)
{
if (padAmount == 1)
{
return str.PadRight(totalLength);
}
return str;
}
int padLeft = padAmount/2 + str.Length;
return str.PadLeft(padLeft).PadRight(totalLength);
}
}
}
-
padChar is unused in this code so why is it there? Perhaps the return lines should be: return str.PadRight(totalLength,padChar); and return str.PadLeft(padLeft).PadRight(totalLength,padChar); Dec 9, 2020 at 14:28
-
After reading this, I would like to provide one other function that is helpful (in printing).
This is not to be taken as an answer to this question, but builds on it.
based on @orad's answer.
public static string PadSplit(string str1, string str2, int totalWidth, char paddingChar = ' ')
{
string output;
int paddingWidth = totalWidth - (str1.Length + str2.Length);
output = string.Format("{0}{1}{2}", str1, string.Empty.PadCenter(paddingWidth, paddingChar), str2);
return output;
}
PadSplit("David", "Wins", 16) => "David Wins"
/* Output looks like this
*****Luke*****
*****Leia*****
*****Han******
**Chewbecca*** */
string result = "";
string names = "Luke,Leia,Han,Chewbecca";
string[] charA = names.Split(',');
for (int i = 0; i < charA.Length; i++)
{
int padLeft = (14 - charA[i].Length) / 2;
string temp = charA[i].PadLeft(charA[i].Length + padLeft, '*');
result += temp.PadRight(14, '*') + "\n";
}
Console.WriteLine(result);
-
3
you can also create your extension like this:
public static string PadBoth(this string s, int padValue)
{
return s.PadLeft(padValue).PadRight(padValue);
}
and use PadBoth method on string.
-
3Try running this, i have a feeling it will do the same thing as pad left alone... Jul 11, 2013 at 10:11
Yourstring.PadLeft().PadRight()
?