typestar

StringBuilder and Format in Visual Basic

Building aligned console output without a thousand concatenations.

Imports System.Text

Dim items = {"espresso", "croissant", "tonic"}
Dim prices = {3.2, 2.75, 4.0}

Dim menu As New StringBuilder()
menu.AppendLine("== cafe menu ==")
For i = 0 To items.Length - 1
    menu.AppendLine($"{items(i),-12}{prices(i),7:F2}")
Next
Console.Write(menu.ToString())

Console.WriteLine(String.Format("mean price: {0:F2}", prices.Average()))
Console.WriteLine($"dearest: {prices.Max():F2}")

How it works

  1. StringBuilder grows text cheaply; AppendLine adds a row at a time.
  2. {items(i),-12} left-pads a column; parentheses index arrays in VB.
  3. String.Format is interpolation's older cousin, placeholders by number.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
405
Tokens
103
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 77 seconds.

Type this snippet

Step 3 of 3 in Variables & strings, step 3 of 29 in Language basics.

← Previous Next →