String.Format
Format strings can compose larger Strings from different values. With the String.Format
Function, we can use format strings to create useful string
representations.
We specify numeric formats, date formats and even padding. Format strings are powerful. But they can be complex and difficult to use.
We pass a format String
as the first argument to String.Format
. The String.Format
function returns the fully composed String
.
Module Module1 Sub Main() Dim name As String = "cat" Dim number As Integer = 10000 Dim day As DateTime = New DateTime(2020, 1, 1) ' Format with String.Format. Dim result As String = String.Format("{0}: {1:0.0} - {2:yyyy}", name, number, day) ' Write result. Console.WriteLine(result) End Sub End Modulecat: 10000.0 - 2020
With the format pattern {0:0.0%}, the second argument is inserted as a percentage. It is multiplied by 100 to yield 73.0% from the number 0.73.
String.Format
, you will get a percentage that is larger than you might want.Module Module1 Sub Main() ' Convert Double to percentage String. Dim ratio As Double = 0.73 Dim result As String = String.Format("String = {0:0.0%}", ratio) Console.WriteLine(result) End Sub End ModuleString = 73.0%
This is also available through format strings. With the -10 code here, the string
is padded to 10 characters with the spaces on the right.
string
is padded to ten characters with the spaces on the left.Module Module1 Sub Main() ' Format String. Dim format As String = "{0,-10} {1,10}" ' Construct lines. Dim line1 As String = String.Format(format, 100, 5) Dim line2 As String = String.Format(format, "Carrot", "Giraffe") Dim line3 As String = String.Format(format, True, False) ' Print them. Console.WriteLine(line1) Console.WriteLine(line2) Console.WriteLine(line3) End Sub End Module100 5 Carrot Giraffe True False
ToString
You do not always need to use String.Format
for formatting patterns. If you have one variable you want to format as a String
, you can usually use ToString
instead.
Module Module1 Sub Main() Dim value As Integer = 123 Dim a As String = String.Format("{0:0000}", value) Dim b As String = value.ToString("0000") ' Print results. They are equal. Console.WriteLine(a) Console.WriteLine(b) End Sub End Module0123 0123
Console.WriteLine
Our examples could be simplified by using Console.WriteLine
directly with a format string
. Console.WriteLine
uses the same format patterns as String.Format
.
Console.WriteLine
function with the same arguments as String.Format
.DateTime
, file nameA common use for String.Format
is for converting a DateTime
to a string
. Once this is done, we can use a DateTime
as a file name.
String
format patterns can be useful. They can help greatly to decrease the complexity of your string
code. Concat
can result in more complex statements.