Imports System
Module StringFormatting
Structure Point
Public X As Integer
Public Y As Integer
End Structure
Sub Main()
' Visual Basic .NET offers excellent support for string formatting.
' Here are some examples of common string formatting tasks.
' Formatting structs
Dim p As New Point With {.X = 1, .Y = 2}
Console.WriteLine("struct1: {0}", p)
' To include field names, we need to explicitly format them
Console.WriteLine("struct2: {{X:{0} Y:{1}}}", p.X, p.Y)
' For a representation similar to source code
Console.WriteLine("struct3: New Point With {{.X = {0}, .Y = {1}}}", p.X, p.Y)
' To print the type of a value
Console.WriteLine("type: {0}", p.GetType())
' Formatting booleans
Console.WriteLine("bool: {0}", True)
' Formatting integers
Console.WriteLine("int: {0}", 123)
' This prints a binary representation
Console.WriteLine("bin: {0}", Convert.ToString(14, 2))
' This prints the character corresponding to the given integer
Console.WriteLine("char: {0}", ChrW(33))
' Hex encoding
Console.WriteLine("hex: {0:X}", 456)
' Formatting floats
Console.WriteLine("float1: {0:F}", 78.9)
' Scientific notation
Console.WriteLine("float2: {0:E}", 123400000.0)
Console.WriteLine("float3: {0:E}", 123400000.0)
' Basic string printing
Console.WriteLine("str1: {0}", """string""")
' To double-quote strings
Console.WriteLine("str2: ""{0}""", """string""")
' Base-16 representation of a string
Console.WriteLine("str3: {0}", BitConverter.ToString(Text.Encoding.Default.GetBytes("hex this")).Replace("-", ""))
' To print a representation of a pointer (address in memory)
Console.WriteLine("pointer: {0}", p.GetHashCode())
' Controlling width and precision
Console.WriteLine("width1: |{0,6}|{1,6}|", 12, 345)
' Width and precision for floats
Console.WriteLine("width2: |{0,6:F2}|{1,6:F2}|", 1.2, 3.45)
' Left-justified width for floats
Console.WriteLine("width3: |{0,-6:F2}|{1,-6:F2}|", 1.2, 3.45)
' Width for strings
Console.WriteLine("width4: |{0,6}|{1,6}|", "foo", "b")
' Left-justified width for strings
Console.WriteLine("width5: |{0,-6}|{1,-6}|", "foo", "b")
' Formatting without printing
Dim s As String = String.Format("sprintf: a {0}", "string")
Console.WriteLine(s)
' Printing to other streams
Console.Error.WriteLine("io: an {0}", "error")
End Sub
End Module