Codiqo

Learn C# · lesson 34 of 61 · about 9 minutes

StringBuilder and Formatting

Put up the guild's hall of fame: build long text efficiently with StringBuilder and line it up with format strings.

What you'll learn

  • Build text with StringBuilder
  • Format numbers with N0, F2 and D3
  • Pad and align columns

The hall of fame

After the battle, the guild's heroes go up on the hall of fame, highest XP first, one neat line each: 01 Bo 120 XP. The lines are added one at a time to a StringBuilder with AppendLine, and the format strings do the lining up: {place:D2} gives the place two digits, {kv.Key,-6} pads the name to 6 characters on the right, and {kv.Value,5} pads the XP to 5 on the left, so the numbers end in a column. The last line is the guild's total, with N0 putting commas in big numbers.

Building and formatting

Each += on a string makes a whole new string. When you build text in a loop, a StringBuilder is faster:

var sb = new StringBuilder(); sb.Append("a"); sb.AppendLine("b"); string s = sb.ToString();

It lives in System.Text, so add using System.Text; at the top.

| Format | Shows |
|---|---|
| {1234567:N0} | 1,234,567 |
| {1234.5:F2} | 1234.50 |
| {7:D3} | 007 |
| {"ab",4} | two spaces, then ab |
| {"ab",-4} | ab, then two spaces |

A receipt

using System.Text;

var sb = new StringBuilder();
string[] items = { "Tea", "Cake", "Sandwich" };
decimal[] prices = { 2.5m, 3.25m, 4.8m };
for (int i = 0; i < items.Length; i++)
{
    sb.AppendLine($"{i + 1:D2} {items[i],-10}{prices[i],6:F2}");
}
sb.Append($"{"Total",-13}{prices.Sum(),6:F2}");
Console.WriteLine(sb.ToString());
Console.WriteLine($"{1234567:N0} visitors");

Output

01 Tea         2.50
02 Cake        3.25
03 Sandwich    4.80
Total         10.55
1,234,567 visitors

Lining up a table

Widths line text up in columns. {name,-6} pads on the right, so the names all start in the same place; {xp,5} pads on the left, so the numbers all end in the same place. A width and a format can go together, the width first: {price,6:F2}.

A small hall of fame

string[] names = { "Bo", "Dee", "Ada" };
int[] xp = { 120, 81, 50 };
for (int i = 0; i < names.Length; i++)
{
    Console.WriteLine($"{i + 1:D2} {names[i],-6}{xp[i],5} XP");
}

Output

01 Bo      120 XP
02 Dee      81 XP
03 Ada      50 XP

Now try it yourself

This lesson is free in Codiqo, with 10 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.