Friday, October 12, 2007

Simulating VB.NET's lost String() function

Before VB.NET was around — back in the days it was just called "Visual Basic" — there was a function named String(), which was used to repeat a character sequence multiple times.

For example, String("Abc", 5) produced "AbcAbcAbcAbcAbc".

In VB.NET, the String() function was dropped, probably because the name conflicts with the construction of a new String value, as in Dim str As New String().

When they dropped it from the language, I would have thought that they would replace it with a new function — maybe something like StrClone().

Searching the web, the question seems to be asked quite often, "How can you do the equivalent of String() in VB.NET?"

Annoyingly, every time it is asked, someone invariably answers by saying they should use the StrDup() function, or New String("A", 5).  They completely disregard that the person wants to concatenate a multi-character string, not one character.

One person even suggested incorrectly that the String constructor could be used to do it — as in New String("Abc", 5) — which it can't.  That would produce a string of 5 "A" characters.

So here is an easy solution.

To create a string consisting of 10 copies of "Abc":

MyString = Replace(Space(10), " ", "Abc")

Or, if you want to use all .NET framework methods (instead of the Visual Basic library), use the following:

MyString = New String(" "c, 10).Replace(" ", "Abc")

Note: the "c" character after the space (" "c) means a literal character (Char) instead of a character string.  It is a tiny efficiency.

Yes, there are other ways of doing this, perhaps by manipulating character arrays.  This, however, is a simple, maintainable — and quick — way of doing it.

With this little trick, you can create your own StrClone() function as follows:

Function StrClone(ByVal Source As String, ByVal Count As Integer) As String
    Return Replace(Space(Count), " ", Source)
End Function

A nice simple function to complete anyone's String library!  Hopefully Microsoft will consider adding this convenience function back into the Visual Basic library.


At 5:37 PM, JADELottery said...

Interesting... nice to know... I read these blogs from time-to-time... great read.

Post a Comment

<< Home