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: 

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. 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. 

public static string Format (string format, object arg0);  
The following code example in Listing 1 inserts a DateTime object in an existing string format.  
/* *** Simple String.Format **/  
string date = String.Format("Today's date is {0}", DateTime.Now);  
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 in C#

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. 

/* *** String.Format with multiple objects **/  
string author = "Mahesh Chand";  
string book = "Graphics Programming with GDI+";  
int year = 2003;  
decimal price = 49.95m;  
string publisher = "APress";  
  
// Book details  
string bookDetails = String.Format("{0} is the author of book {1} \n " +  
"published by {2} in year {3}. \n Book price is ${4}. ",  
author, book, publisher, year, price);  
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 C#

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. 

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. 

Console.WriteLine("***** Alignment ****/");  
string[] books = {"A Programmer's Guide to ADO.NET", "Graphics Programming", "Programming C#"};  
string[] publishers = {"APress", "Addision Wesley", "C# Corner" };  
decimal[] prices = { 45.95m, 54.95m, 49.95m };  
int[] years = { 2001, 2002, 2003 };  
  
Console.WriteLine("Mahesh Chand's Books");  
String data = String.Format("{0,-35} {1,-20} {2,-10} {3, -10} \n",  
"Title", "Publisher", "Price", "Year");  
for (int index = 0; index < years.Length; index++)  
data += String.Format("{0,-35} {1,-20} {2, -10} {3, -10} \n",  
books[index], publishers[index], prices[index], years[index]);  
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.  

// Number formatting  
int num = 302;  
string numStr = String.Format("Number {0, 0:D5}", num);  
Console.WriteLine(numStr);  
  
// Decimal formatting  
decimal money = 99.95m;  
string moneyStr = String.Format("Money {0, 0:C2}", money);  
Console.WriteLine(moneyStr);  
  
// DateTime formatting  
DateTime now = DateTime.Now;  
string dtStr = String.Format("{0:d} at {0:t}", now);  
Console.WriteLine(dtStr);

Listing 4.

The output of Listing 3 looks like Figure 4.

String.Format()

Figure 4

Summary

In this code example, we learned how to format strings in C# using String.Format method. 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.