6

I have a string (like below), and I want each of the argument to be center aligned.

There is an option for left align that is ("+") and right align that is ("-") but I want to center align.

basketItemPrice = string.Format("\n\n{0, -5}{1, -14:0.00}{2, -18:0.00}{3,-14:0.00}{4,6}{5,-12:0.00}", item.Quantity, item.OrderItemPrice, item.MiscellaniousCharges, item.DiscountAmountTotal, "=", item.UpdateItemAmount(Program.currOrder.OrderType));
Eliahu Aaron
  • 4,103
  • 5
  • 27
  • 37
NoviceToDotNet
  • 10,387
  • 36
  • 112
  • 166
  • 2
    Please rephrase. Center of what? – Simon Whitehead Sep 02 '13 at 12:14
  • 3
    I don't believe format strings support centered alignment, only right or left adjusted. From [the doc](http://msdn.microsoft.com/en-us/library/system.string.format.aspx): "_alignment_ Optional. A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). If you omit alignment, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces." They mention no centering option. – Jeppe Stig Nielsen Sep 02 '13 at 12:16
  • center of the space length.. – NoviceToDotNet Sep 02 '13 at 12:18
  • Some elements have the property StringFormat.Alignment, like Label. The string class itself does not. – MrFox Sep 02 '13 at 12:19
  • I am using no control..it's direct string drawing to a rectagle – NoviceToDotNet Sep 02 '13 at 12:20
  • 1
    @SimonWhitehead With `string.Format` method, your format string may contain one or more format items which have a comma after the index and then give the width of the "cell" into which the object is put. If the width is positive, right-alignment is used; if it is negative, left-alignment. For example `string.Format("{0,-5}", obj)` versus `string.Format("{0,5}", obj)` where `obj` is some object whose string representation is less than five characters long. – Jeppe Stig Nielsen Sep 02 '13 at 12:30
  • @Jeppe I was aware.. I mistakenly assumed the question was about rendering a string somewhere.. not the string itself. Whoops. – Simon Whitehead Sep 02 '13 at 12:48

4 Answers4

16

Unfortunately, this is not supported natively by String.Format. You will have to pad your string yourself:

static string centeredString(string s, int width)
{
    if (s.Length >= width)
    {
        return s;
    }

    int leftPadding = (width - s.Length) / 2;
    int rightPadding = width - s.Length - leftPadding;

    return new string(' ', leftPadding) + s + new string(' ', rightPadding);
}

Usage example:

Console.WriteLine(string.Format("|{0}|", centeredString("Hello", 10)));
Console.WriteLine(string.Format("|{0}|", centeredString("World!", 10)));
Heinzi
  • 167,459
  • 57
  • 363
  • 519
7

I tried to make an extension method which still preserves the IFormattable support. It uses a nested class which remembers the raw value and the desired width. Then when format string is provided, it is used, if possible.

It looks like this:

public static class MyExtensions
{
    public static IFormattable Center<T>(this T self, int width)
    {
        return new CenterHelper<T>(self, width);
    }

    class CenterHelper<T> : IFormattable
    {
        readonly T value;
        readonly int width;

        internal CenterHelper(T value, int width)
        {
            this.value = value;
            this.width = width;
        }

        public string ToString(string format, IFormatProvider formatProvider)
        {
            string basicString;
            var formattable = value as IFormattable;
            if (formattable != null)
                basicString = formattable.ToString(format, formatProvider) ?? "";
            else if (value != null)
                basicString = value.ToString() ?? "";
            else
                basicString = "";

            int numberOfMissingSpaces = width - basicString.Length;
            if (numberOfMissingSpaces <= 0)
                return basicString;

            return basicString.PadLeft(width - numberOfMissingSpaces / 2).PadRight(width);
        }
        public override string ToString()
        {
            return ToString(null, null);
        }
    }
}

Note: You have not indicated if you want the one "extra" space character put to the left or to the right in cases where an odd number of space characters needs to be appended.

This test seems to indicate it works:

double theObject = Math.PI;
string test = string.Format("Now '{0:F4}' is used.", theObject.Center(10));

Of course, format string F4 with a double means "round to 4 decimal places after the decimal point".

Jeppe Stig Nielsen
  • 60,409
  • 11
  • 110
  • 181
0

I am not sure to understand your question but I hope this helps you:

public static class StringHelper
{
    public static string Center(this String value, int width)
    {
        var padding = (width + value.Length) / 2;
        return value.PadLeft(padding, '#');
    }
}
  • Ok what do you mean correctly here? Correctly according to what? – Vladimir Kniazkov Sep 03 '13 at 11:14
  • Have you tried examples like `"Hello".Center(40)` with your code? It gives _six_ spaces followed by `Hello` followed by zero spaces. I can't see how that is centered or how it is related to the `40` I specified. Therefore I conclude that your code seems to not work. – Jeppe Stig Nielsen Sep 03 '13 at 11:57
  • For example you have a line with length 100 and you want to put your string on the middle of this line. You do next: var line = "Hello".Center(100). Your hello string puts in the middle of this line. But maybe this question means something else – Vladimir Kniazkov Sep 03 '13 at 12:44
  • No. Please try your own example for yourself, with your code. `"Hello".Center(100)` does ***not*** put "Hello" on the center of a line with length 100. – Jeppe Stig Nielsen Sep 03 '13 at 15:11
  • 2
    `return value.PadLeft( (width + value.Length) / 2 ).PadRight(width);` – Slai May 02 '16 at 11:31
  • Thank you Slai for your comment – Vladimir Kniazkov Oct 20 '17 at 09:03
-3

If you are drawing onto a bitmap use Graphics.DrawString(..) method with a string alignment set to center.

Plenty of examples here:

http://msdn.microsoft.com/en-us/library/system.drawing.stringformat.linealignment.aspx

Mesh
  • 6,262
  • 5
  • 34
  • 53
  • 1
    Seems irrelevant. Look at the question. He uses the static method `Format` on the class `string` (also known as `System.String`). He doesn't use the class you are linking. – Jeppe Stig Nielsen Sep 02 '13 at 12:36
  • One of his comment mentions drawing directly...and we don't know what he does with the string once formatted. He could be outputting it in a mono-spaced font. Oh and thanks for the `string = System.String` really useful! – Mesh Sep 02 '13 at 12:47