Here shows 2 ways to implement string interpolation, they should be very useful for formatting output string.
Of course, passing more arguments is acceptable.
We sometimes may need to design a shared function for general purpose. So, using array should get more flexibility in various cases.
If you put dollar sign before a variable you will see the warning like below picture.
String.Format Method
This method is very common and easy to use for outputting string. Just put the string or variable after first argument.
Dim strOutputString As String = "The price of {0} is {1}."
Debug.Print(String.Format(strOutputString, "book", "10"))
'The price of book is 10.
Of course, passing more arguments is acceptable.
Dim strOutputString As String = "The price of {0} is {1}, and buy {2} get {3} free."
Debug.Print(String.Format(strOutputString, "book", "10", "2", "1"))
'The price of book is 10, and buy 2 get 1 free.
We sometimes may need to design a shared function for general purpose. So, using array should get more flexibility in various cases.
Dim strOutputString As String = "The price of {0} is {1}."
Dim arrOutputParams As String() = {"book", "10"}
Debug.Print(String.Format(strOutputString, arrOutputParams))
'The price of book is 10.
Dollar Sign
Dollar sign will lead string to be treated as a template string, but it must be assigned with string value due to it needs to be recognized by compiler.
Dim strProduct As String = "book"
Dim strPrice As String = "10"
Dim strOutputString As String = $"The price of {strProduct} is {strPrice}."
Debug.Print(strOutputString)
'The price of book is 10.
strProduct = "pecil"
strPrice = "5"
strOutputString = $"The price of {strProduct} is {strPrice}."
Debug.Print(strOutputString)
'The price of pecil is 5.
If you put dollar sign before a variable you will see the warning like below picture.
Hello thank you for the explain, i would like to add a code that use in text the { some text code } and because of this, gives me error, how can i include it without any error ?
ReplyDeleteThank you in advance.
Sorry, I cannot give you any opinion due to I don't know the exact code that you use. You could directly try those examples written in this article, and then you may find the problem by yourself.
DeleteThanks for your comment.