Using .NET Interops in VBScript - Working with Strings
(Page 3 of 4 )
.NET interops can also be used to do some advanced string manipulation. One example of this is the ability to produce formatted strings. Formatted strings are dynamically generated strings. Take this classic VBScript example.
arrOne = Array(1, "loneliest")
arrTwo = Array(2, "happiest")
WScript.Echo arrOne(0) & " is a " & arrOne(1) & " number"
WScript.Echo arrTwo(0) & " is a " & arrTwo(1) & " number"
This code uses some array data to dynamically construct string output. This is the same technique you've seen used over and over again to produce an output like the following:
1 is a loneliest number
2 is a happiest number
A formatted string would be one whole string that contained markers where the array data could be inserted without having the mess of concatenating several strings into one.
Set sb = CreateObject("System.Text.StringBuilder")
sb.AppendFormat_5 Nothing, "{0} is a {1} number" & vbCrLf, Array(1, "loneliest")
sb.AppendFormat_5 Nothing, "{0} is a {1} number" & vbCrLf, Array(2, "happiest")
WScript.Echo sb.ToString()
Here we're using a single string of the form "{0} is a {1} number." Each number in brackets indicates a marker where a substring is to be inserted. The substrings are found in the array provided.
Once all substitutions have been made, they are added to the StringBuilder object using the AppendFormat_5 method. As it turns out, the AppendFormat method of the StringBuilder object is an overloaded method. This means that there are several different methods with the same name that accept different types of parameters. Since VBScript does not support overloaded methods, each of these overloads are exposed by the COM object as separate, numbered methods. In this case, we're using the fifth overloaded AppendFormat method.
The StringBuilder object then provides a ToString method that returns a single string that has been constructed.
Next: More with StringBuilder >>
More Windows Scripting Articles
More By Nilpo