Mega Code Archive

 
Categories / C# Book / 02 Essential Types
 

0247 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: A comma and a minimum width to apply A colon and a format string 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