WeCodeAcademy

C# String Formatting and StringBuilder

ExampleC#
using System;
using System.Text;

class Program
{
    static void Main()
    {
        int n = 42;
        Console.WriteLine($"{n,6}|");
        Console.WriteLine($"{n,-6}|");
        Console.WriteLine($"{n:D5}");
        Console.WriteLine($"{255:X}");
        Console.WriteLine(string.Format("{0} and {1}", "a", "b"));

        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= 3; i++)
        {
            sb.Append("[").Append(i).Append("]");
        }
        sb.AppendLine();
        sb.Append("end");
        Console.WriteLine(sb.ToString());
        Console.WriteLine(sb.Length);
        Console.WriteLine("abc".PadLeft(5, '*'));
        Console.WriteLine(string.IsNullOrEmpty(""));
    }
}
Output
    42|
42    |
00042
FF
a and b
[1][2][3]
end
13
**abc
True

StringBuilder is the efficient way to build text in a loop. The length counts [1][2][3] (9 characters), the line break and end (3 characters). The line break is one character on Linux and macOS, so the output shows 13; on Windows it is two characters and the length is 14.

Quick check

Which type builds long strings efficiently?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.