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
StringBuildergrows text cheaply;AppendLineadds a row at a time.{items(i),-12}left-pads a column; parentheses index arrays in VB.String.Formatis interpolation's older cousin, placeholders by number.
Keywords and builtins used here
DimForImportsNewNextStringTo
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.
Step 3 of 3 in Variables & strings, step 3 of 29 in Language basics.