Creating and accessing a substring in VB Script

Viewed 37

I am trying to create a simple string in VB script and then I would like to create an array with substrings from the original array. Then I may change the values as necessary. For example:

Full_string = "XYZABC"

Then, say I want an array comprising of two elements from Full_string:

'NA(0) = "XY"
NA(1) = "ZA"
NA(2) = "BC"'

Then if needed I want to change as follows:

NA(0)(0) = "D"

How can I do all these in VBScript?

1 Answers

Create a two dimensional array based on the string size and the number of characters you want to break on (two in your example) and then iterate through the string to populate the array, like this:

FullString = "XYZABC"
BreakOn = 2

'Create a two dim array of correct size
ArraySize = Int(Len(FullString)/BreakOn)
ReDim aString(ArraySize,BreakOn)

'Populate array
j = 0
For i = 1 To Len(FullString) Step BreakOn
  For x = 0 To BreakOn - 1
    aString(j,x) = Mid(FullString,i+x,1)
  Next
  j = j + 1
Next

'Display array contents
For i = 0 To UBound(aString)
  WScript.Echo "---"
  For x = 0 To BreakOn - 1
    WScript.Echo aString(i,x)
  Next
Next

'Demonstrate change of array element
WScript.Echo aString(0,0)
aString(0,0) = "D"
WScript.Echo aString(0,0)
Related