CSharp - String String Format

Introduction

Format method can build strings with embed variables.

The embedded variables can be of any type and the Format calls ToString on them.

The string containing the embedded variables is called a composite format string.

Demo

using System;
class MainClass//from w w w .  ja  v a 2s  .c  om
{
   public static void Main(string[] args)
   {
         string composite = "New {0} tutorial are added in {1} on this {2} morning";
         string s = string.Format (composite, 3, "the morning", DateTime.Now.DayOfWeek);
         Console.WriteLine(s);
   }
}

Result

To use interpolated string literals, precede the string with the $ symbol and put the expressions in braces:

Demo

using System;
class MainClass/*from  w  ww. j a  v  a  2s  .  c  o m*/
{
   public static void Main(string[] args)
   {
       string s = $"{DateTime.Now.DayOfWeek} morning";
       Console.WriteLine(s);

   }
}

Result

The number corresponds to the argument position and is optionally followed by:

  • A comma and a minimum width to apply
  • A colon and a format string

The minimum width is useful for aligning columns.

If the value is negative, the data is left-aligned; otherwise, it's right-aligned. For example:

Demo

using System;
class MainClass//  w ww. java  2 s .co m
{
   public static void Main(string[] args)
   {
     string composite = "Name={0,-20} Credit Limit={1,15:C}";

     Console.WriteLine (string.Format (composite, "Mary", 500));
     Console.WriteLine (string.Format (composite, "Elizabeth", 20000));

   }
}

Result