String format

String format requires two parts.

The first part is the format string.

The second is the target items.


using System;

class Sample
{
    public static void Main()
    {
        string composite = " {0} / {1} - {2} ";
        string s = string.Format(composite, 5, "AA", DateTime.Now.DayOfWeek);

        Console.WriteLine(s);

    }
}

The output:


5 / AA - Wednesday

The number in the curly braces specifies the index of the item.

To add format to each item we can add format infomation for each item following the index number:


using System;

class Sample
{
    public static void Main()
    {
        string composite = "Name={0,-20} Account={1,15:C}";

        Console.WriteLine(string.Format(composite, "M", 999999));
        Console.WriteLine(string.Format(composite, "A", 20000));

    }
}

The output:


Name=M                    Account=    $999,999.00
Name=A                    Account=     $20,000.00
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.