C# String Formatting
Composite formatting builds a string from a template with numbered placeholders. string.Format fills each placeholder with a value from the argument list.
Fill Placeholders by Number
The template holds the placeholders {0} and {1}. string.Format fills them with the name and the score.
using System;
class Program
{
static void Main(string[] args)
{
string line = string.Format("{0} scored {1} points", "Hana", 88);
Console.WriteLine(line);
}
}Reuse a Placeholder
The placeholder {0} appears twice in this template. Both spots fill with the first value.
using System;
class Program
{
static void Main(string[] args)
{
string line = string.Format("{0} vs {1}: {0} wins", "Nova", "Comet");
Console.WriteLine(line);
}
}Align Values in Columns
The placeholder {0,-6} left-aligns the name in six characters. The placeholder {1,4} right-aligns the number in four characters.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(string.Format("{0,-6}|{1,4}", "Name", 42));
}
}Example
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(string.Format("{0,-6}|{1,4}", "Item", "Qty"));
Console.WriteLine(string.Format("{0,-6}|{1,4}", "Pens", 8));
Console.WriteLine(string.Format("{0,-6}|{1,4}", "Rulers", 5));
}
}Key points
- The placeholder {0} stands for the first value after the template.
- The placeholder {1} stands for the second value.
- One placeholder can appear in the template more than once.
- A number after a comma in a placeholder sets the field width.
- A positive width pads on the left, so the value aligns to the right.
- A negative width pads on the right, so the value aligns to the left.
- Interpolation suits a line read in code. Composite format strings suit columns that must line up.
In this example, each line uses the same format string. The first field holds six characters and aligns left. The second field holds four characters and aligns right. Rulers fills the first field in full, so no padding follows it.
Note
Placeholder numbers count from zero. The first value is number 0, not number 1.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the placeholder {1,4} do in a format string?