views:

127

answers:

6

In C#, I have a width I want to use for some strings, but I won't know that width until runtime. I'm doing something like this:

string.Format("{0, " + digits + "}", value)  // prints 123 as "  123"

Is there a string formatting directive that lets me specify this without smashing my own format string together like this?

I looked around on MSDN for a little while and I feel like I'm missing a whole chapter on format strings or something.

+1  A: 

you can do something like

string test = valueString.PadLeft(10,' ');

or even sillier

string spaces = String.Concat(Enumerable.Repeat(" ", digits).ToArray());
Stan R.
masochistic.... PadLeft.
Michael Bray
hahah i know, its pretty funny that i missed padleft, i found it as soon as i wrote that.
Stan R.
+1  A: 

You can use the PadLeft and PadRight methods:

http://msdn.microsoft.com/en-us/library/system.string.padleft%28VS.71%29.aspx

BFree
+4  A: 

Take a look at PadLeft:

s = "123".PadLeft(5);  // Defaults to spaces
s = "123".PadLeft(5, '.');  // Pads with dots
Michael Bray
i'll +1 you, because im embarrassed i forgot about padleft, it was on the tip of my tounge.
Stan R.
A: 

The functions mentioned by others will work, but this MSDN page has a more general solution to formatting that changes at runtime:

Composite Formatting

They give examples much like yours.

Edit: I thought you were trying to solve the general case of composing a format string at runtime. For example, if there were no built in PadLeft(), you could do this:

    int myInt = 123;
    int nColumnWidth = 10;

    string fmt = string.Format("Price = |{{0,{0}}}|", nColumnWidth);

    // now fmt = "Price = |{0,5}|"

    string s = string.Format(fmt, myInt);

You can even do all that in one line, but it's ugly:

    string s = string.Format(
            string.Format("Price = |{{0,{0}}}|", nColumnWidth),
            myInt);
egrunin
Maybe I'm blind but I'm not seeing any example on that page that does something quite like what I'm doing.
Ken
A: 

Perhaps this will help with your research on formatting:

Formatting Types
Composite Formatting

However, I don't think you're going to do much better than this, as the alignment parameter must be part of the format string and does not seem to be represented by a property.

cpkilekofp
If "the alignment param must be part of the format string", that answers my question: it's not possible from string.Format. I figured there would be some way to use params, like `(format nil "~vD" digits value)` in Lisp -- I know Lisp's `format` is a lot more powerful in general, but I figured using a param was basic enough. Thanks!
Ken
A: 

Probably overkill but just to illustrate a way to encapsulate the format specification and use an overload of String.Format that accepts an IFormatProvider.

class Program
{
    public static void Main(string[] args)
    {
        int digits = 7;
        var format = new PaddedNumberFormatInfo(digits);
        Console.WriteLine(String.Format(format, "{0}", 123));
    }
}
class PaddedNumberFormatInfo : IFormatProvider, ICustomFormatter
{
    public PaddedNumberFormatInfo(int digits)
    {
        this.DigitsCount = digits;
    }

    public int DigitsCount { get; set; }

    // IFormatProvider Members
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof(ICustomFormatter))
            return this;

        return null;
    }
    // ICustomFormatter Members
    public string Format(string format, object arg, IFormatProvider provider)
    {
        return String.Format(
            String.Concat("{0, ", this.DigitsCount, "}"), arg);
    }
}
João Angelo