none
Variable padding for String.Format() RRS feed

  • Question

  • Hi,

    the question have been asked before but none of my tests works and I don't know why.

    string name1 = "TEST";
    string name2 = "Description";
    maxLength = 10;
    string format = "{0:" + maxLength + "} = {1}";
    buffer = string.Format(format, name1, name2);

    The debugger show me :

    format = "{0:10} = {1}"
    buffer = "TEST = Description"

    Why no space is inserted for 'TEST' string ?

    Thanks,

    Vincent

    Friday, July 17, 2015 11:26 PM

Answers

  • According to the documentation, the format component of the composite formatting string doesn't do anything for strings, only numeric types, Enums and DateTimes. If you want to pad your string, you can use the PadRight method.

    buffer = string.Format(format, name1.PadRight(10), name2);

    Saturday, July 18, 2015 12:22 AM