tags:

views:

80

answers:

4

Some of us unfortunately are still supporting legacy app like vb6 I have forgotten how to parse a string

given a string dim mystring as string ="1234567890"

how do you loop in vb6 through each character and so something like

   for each character in mystring
      debug.print character
   next

in c# i would do

char[] myChars = mystring.ToCharArray(); foreach (char c in theChars) { //do something with c }

Any ideas?

Thanks a lot

+6  A: 

You can use the 'Mid' function to get at the individual characters:

Dim i As Integer
For i = 1 To Len(mystring)
    Print Mid$(mystring, i, 1)
Next

Note this is untested.

Erik Forbes
Please use `Mid$` instead of `Mid` - It's more efficient and type-safe since no variants are used.
Dario
Sorry - it's been years since I used VB6. I'll amend the answer.
Erik Forbes
+2  A: 

There is no possibility to use foreach on strings.

Use

Dim i As Integer

For i = 1 To Len(YourString)
    Result = Mid$(YourString, i, 1)
Next

note that the type of Result is a length-1 string, no char or byte type.

If performance is important, you'll have to convert the string to a bytearray fist (using StrConv) and then loop through it like this.

Dim i As Long
For i = 0 To UBound(Data)
    Result = Data(i) ' Type is Byte '
Next

This is much more efficient.

Dario
thanks that worked!!Grateful
jo
Be aware that if you convert the string to a byte array using StrConv you are also converting it from Unicode to "ANSI" using the current system code page.
MarkJ
A: 

The easiest way is to convert the string into an array of bytes and iterate over the byte array (converting each byte to a character).

Dim str As String
Dim bytArray() As Byte
Dim count As Integer

str = "This is a string."
bytArray = str

For count = 0 To UBound(bytArray)
    Debug.Print Chr(bytArray(count))
Next
mkedobbs
Doesn't work like one could expect because theare are lots of empty bytes. Note that you can't apply `Chr` on a byte but only on strings.
Dario
Be aware that if you convert the string to a byte array like that you are also converting it from Unicode to "ANSI" using the current system code page.
MarkJ
+1  A: 

Don't loop; rather, set a reference to Microsoft VBScript Regular Expressions library and use regular expressions to achieve your 'do something' goal.

onedaywhen
+1 worth considering. Here's a link http://www.regular-expressions.info/vb.html
MarkJ