Use Of String.Format() To Format Strings In C#

In this article, you will learn how to format strings in C#. C# String Format method converts an object into a string. C# sample code formats strings and other data types to string using C# in .NET Core.

Introduction to C# String Format

C# String.Format() method formats strings in a desired format by inserting objects and variables with specified space and alignments into other strings. It is often used to also format strings into specific formats.
 
Note:
String Interpolation is the way to format a string in C# 6.0 or later versions. Learn String Interpolation here.
 
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);  
Where,
  • 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.
 

Insert a single object in a 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.
 
Format-String-CSharp
Figure 1.
 

Insert multiple objects in a 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";  
  7.   
  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 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 };  
  6.   
  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 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 ‘:’. 
  1. String.Format("{index[,alignment][:formatString]}"object);  
  2. The following code example in Listing 4 uses format specifiers for number, decimal, and date respectively.  
  3. // Number formatting  
  4. int num = 302;  
  5. string numStr = String.Format("Number {0, 0:D5}", num);  
  6. Console.WriteLine(numStr);  
  7.   
  8. // Decimal formatting  
  9. decimal money = 99.95m;  
  10. string moneyStr = String.Format("Money {0, 0:C2}", money);  
  11. Console.WriteLine(moneyStr);  
  12.   
  13. // DateTime formatting  
  14. DateTime now = DateTime.Now;  
  15. string dtStr = String.Format("{0:d} at {0:t}", now);  
  16. Console.WriteLine(dtStr);  
Listing 4.
 
The output of Listing 3 looks like Figure 4.
 
String.Format()
Figure 4