Take the following parameter as the field width in String.Format

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

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

Is there a line formatting directive that allows me to specify this without breaking my own format string like that?

I looked around a bit on MSDN and it seems to me that I'm missing a whole chapter on format strings or something like that.

+5
source share
8 answers

Take a look at PadLeft:

s = "123".PadLeft(5);  // Defaults to spaces
s = "123".PadLeft(5, '.');  // Pads with dots
+7
source

you can do something like

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

or even sillier

string spaces = String.Concat(Enumerable.Repeat(" ", digits).ToArray());
+2
source

, , , MSDN , :

, .

: , . , PadLeft() , :

    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);

, :

    string s = string.Format(
            string.Format("Price = |{{0,{0}}}|", nColumnWidth),
            myInt);
+1

, :


, , , , , - .

0

, , String.Format, 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);
    }
}
0

CodeProject, , .

: # .

FormatEx, String.Format, , formatString.

FormatEx("{0,{1}:{2}}", value, width, formatString);

varArgs 0 , varArgs 1, String, varArgs 2.

: , . formatString. " ".

-Jesse

0

String , , n .

https://msdn.microsoft.com/en-us/library/xsa4321w(v=vs.110).aspx

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

All Articles