Can String.Format() be implemented in VB6, at least a close-enough version of it that could be useful when programming in good ol’ VB6?
Good resource on the matter of VB6 string manipulation performance: http://www.aivosto.com/vbtips/stringopt2.html
On a related not, I also came up with a couple string comparison functions, find them here on CodeReview.SE
These functions are tremendously useful for improving VB6 readability, especially if you’ve been spoiled with .net code lately and suddenly are required to dive into a VB6 code base… Enjoy!
I couldn’t find one anywhere, so I made my own:
Notice the
ParamArrayin the method signature (thanks @wqw): doing so spares the usage of multiple optional parameters (and from usage bugs with being able to assignvalue2without assigningvalue1when naming the parameters in the calling statement). Because it’s aParamArray, the individual values areVariantwhich means every parameter could be of a different type, VB is doing the string conversion behind the scenes.The function can then be consumed like this:
Output:
And also like this:
Output:
Also possible to specify alignment (/padding) and to use escape sequences:
Looking at samples from http://msdn.microsoft.com/fr-fr/library/b1csw23d(v=vs.80).aspx, only a few format specifiers are not implemented, mostly date/time specifiers… but I would think the “c” custom date/time format specifier makes it up.
The function uses a straightforward implementation of
String.Contains():EDIT: This code now properly handles “\\” escapes, as mentioned in the comments. Also, while
StringContainsis certainly practical and gives a more comfortable reading than anInStr()call, the belowStringContainsAnyfunction is even better:Consider the following:
Before VB can determine if
fooisTRUEorFALSE, every singleInStr()call is made. However withStringContainsAny(), the condition is satisfied with the first value that gets found, which makes it a faster statement.EDIT: Previous edit pretty much wiped out escape sequences; reinstated them, using a small class “EscapeSequence” exposing two properties and a factory method – doing this allows keeping the for-each loop and handling all simple escapes without duplicating much code.
This code also uses a
StringStartsWithfunction, implemented like this: