Re: VBscript Array Split Function

Tech-Archive recommends: Fix windows errors by optimizing your registry



Richard Mueller [MVP] schrieb:
"ekkehard.horner" <ekkehard.horner@xxxxxxxx> wrote in message news:49d244ea$0$30227$9b4e6d93@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
turtle schrieb:
Hello,

I would like to create a function within a VBScript where I will enter
a string (i.e person's first name) and that person's first name is
inputted into an array so that each separate character in the array is
a letter of the name inputted.
[...]
Richard Mueller's solution is therefore to be preferred; but it can be optimized,
because the size of the array is known before the loop:

UBound( array ) == Len( string ) - 1.

Avoiding the costly ReDim Preserve operation removes a second problem of this code.
For the empty string the result is set to

Dim arrChars()

That statement creates a fixed array with no elements - something that doesn't
make sense and can't be handled properly by VBScript (see output line 6).
[...]
Code to illustrate:
[...]
On Error Resume Next
vUB = UBound( aChars )
If 0 <> Err.Number Then vUB = Err.Description
output:
[...]
6 >< RM () Wahr Variant() Index außerhalb des gültigen Bereichs
[...]

I agree that you can ReDim the array ahead of time and this is more efficient than ReDim'ing after processing each character. However, I think an empty array is useful. If the input string is empty, UBound will be -1, and the For Each loop will not echo anything, but will also not raise an error. For example:
=========
Option Explicit
Dim strValue, strChar, k, arrChars()

strValue = "Larry"
strValue = ""

ReDim arrChars(Len(strValue) - 1)

For k = 1 To Len(strValue)
strChar = Mid(strValue, k, 1)
arrChars(k - 1) = strChar
Next

For Each strChar In arrChars
Wscript.Echo strChar
Next

"Dim arrChars()" creates a fixed empty array - you can't let it grow,
because it is fixed and you can't store anything in it, because it
has no slots. That even VBScript does not like such abominations can
be seen by the error thrown as soon as you try to access its UBound.

The name "arrChars" will be reused when you create the dynamic array with
(currently) Len(strValue) slots. If you just use the ReDim - which is
perfectly ok with Option Explicit - you avoid

the misleading insinuation of using a fixed array - as in
case of "Dim arrChars( <NiceNumber> )"

whatever action VBScript has to take to create that beast (for
nothing)

the risk of (mis)using arrChars() before its re-definition


.


Quantcast