How To Format Strings In C#

C# string format method formats strings in .NET. String.Format() manages formatting including the position, alignment, and format type. String.Format method has 8 overloaded formats to provide options to format various objects and variables that allows various variables to format strings. The simplest form of String.Format is the following: 
  1. String.Format("{index[,alignment][:formatString]}"object);  
  • index - The zero-based index of the argument whose string representation is to be included at this position in the string. If this argument is null, an empty string will be included at this position in the string.
  • alignment - Optional. A signed integer that indicates the total length of the field into which the argument is inserted and whether it is right-aligned (a positive integer) or left-aligned (a negative integer). If you omit alignment, the string representation of the corresponding argument is inserted in a field with no leading or trailing spaces.
  • If the value of alignment is less than the length of the argument to be inserted, alignment is ignored and the length of the string representation of the argument is used as the field width.
  • formatString - Optional. A string that specifies the format of the corresponding argument's result string. If you omit formatString, the corresponding argument's parameterless ToString method is called to produce its string representation. If you specify formatString, the argument referenced by the format item must implement the IFormattable interface. 
Note: In C# 6 or later versions, String Interpolation is recommended. Sting interpolation is more flexible and more readable and can achieve the same results without composite formatting. Learn C# String Interpolation here. 

Insert a single object in a C# string

We can insert one or more objects and expressions in a string at a specified position using the String.Format method. The position in the string starts at 0th index.
For a single object formatting, the first argument is the format and the second argument is the value of the object. The object is replaced at the {0} position in the string. 
  1. public static string Format (string format, object arg0);  
  2. The following code example in Listing 1 inserts a DateTime object in an existing string format.  
  3. /* *** Simple String.Format **/  
  4. string date = String.Format("Today's date is {0}", DateTime.Now);  
  5. Console.WriteLine(date);  
Listing 1.
As you can see from the above code example, {0} is at the last potion in the string and the second argument is a DateTime.Now. In this case, string portion {0} will be replaced by the value of DateTime.Now in the string. Figure 1 is the result of above code in Listing 1.
Figure 1.

Insert multiple objects in a C# string

We can insert multiple objects or expressions in a string to give it a desired format. The following code example in Listing 2 creates a string by inserting 5 objects. 
  1. /* *** String.Format with multiple objects **/  
  2. string author = "Mahesh Chand";  
  3. string book = "Graphics Programming with GDI+";  
  4. int year = 2003;  
  5. decimal price = 49.95m;  
  6. string publisher = "APress";  
  8. // Book details  
  9. string bookDetails = String.Format("{0} is the author of book {1} \n " +  
  10. "published by {2} in year {3}. \n Book price is ${4}. ",  
  11. author, book, publisher, year, price);  
  12. Console.WriteLine(bookDetails);  
Listing 2.
As you can see from the above code example, the String.Format has placeholders for objects, starting at the 0th to 4th index. The {0} is replaced by the first object passed in the method, {1} is replaced by the second object passed in the method and so on.
The output of Listing 2 looks like Figure 2.
String Format CSharp .NET
Figure 2.

Alignment and spacing using C# String Format

Besides the index, alignment and formatString are two optional arguments of String.Format method. Alignment is followed by index and separated by a comma as you can see in the following syntax. 
  1. String.Format("{index[,alignment][:formatString]}"object);  
By default, strings are right-aligned within their field if you specify a field width. To left-align strings in a field, you preface the field width with a negative sign, such as {0,-12} to define a 12-character right-aligned field.
The following code example in Listing 3 creates a formatted table of items with spacing between items that displays a list of published books with their title, price, publisher, and year published. 
  1. Console.WriteLine("***** Alignment ****/");  
  2. string[] books = {"A Programmer's Guide to ADO.NET""Graphics Programming""Programming C#"};  
  3. string[] publishers = {"APress""Addision Wesley""C# Corner" };  
  4. decimal[] prices = { 45.95m, 54.95m, 49.95m };  
  5. int[] years = { 2001, 2002, 2003 };  
  7. Console.WriteLine("Mahesh Chand's Books");  
  8. String data = String.Format("{0,-35} {1,-20} {2,-10} {3, -10} \n",  
  9. "Title""Publisher""Price""Year");  
  10. for (int index = 0; index < years.Length; index++)  
  11. data += String.Format("{0,-35} {1,-20} {2, -10} {3, -10} \n",  
  12. books[index], publishers[index], prices[index], years[index]);  
  13. Console.WriteLine($"\n{data}");  
Listing 3.
The output of Listing 3 looks like Figure 3.
String.Format() Method
Figure 3.

Format using C# String Format

The formatString optional arguments of String.Format method defines how an object is formatted. All standard and custom formats may be applied to the string. Check out Formatting Types in .NET to learn more about formats and their syntaxes.
As defined in the following syntax, the format specifier is followed by a colon ‘:’. 
String.Format("{index[,alignment][:formatString]}", object);
The following code example in Listing 4 uses format specifiers for number, decimal, and date respectively.
  1. // Number formatting  
  2. int num = 302;  
  3. string numStr = String.Format("Number {0, 0:D5}", num);  
  4. Console.WriteLine(numStr);  
  6. // Decimal formatting  
  7. decimal money = 99.95m;  
  8. string moneyStr = String.Format("Money {0, 0:C2}", money);  
  9. Console.WriteLine(moneyStr);  
  11. // DateTime formatting  
  12. DateTime now = DateTime.Now;  
  13. string dtStr = String.Format("{0:d} at {0:t}", now);  
  14. Console.WriteLine(dtStr);  
Listing 4.
The output of Listing 3 looks like Figure 4.
Figure 4
In this code example, we learned how to format strings in C# using String.Format method.