.Substring out of range

mevets

Member
Joined
Jun 22, 2006
Messages
17
Location
Northern, VA
Programming Experience
Beginner
I don't understand how this example is out of range:
VB.NET:
        Dim strText As String = "Gui, Add, Text, vhi ghi, Hello"
        Dim intTextLen As Integer = strText.Length
        Dim posDlmtr As integer
        Dim i As Integer = 1
        Dim canLoop As Boolean = True

        Do While canLoop = True
            intTextLen = strText.Length
            posDlmtr = InStr(strText, ", ")
            If posDlmtr > 0 Then
                strText = strText.Substring(posDlmtr + 2, intTextLen - posDlmtr + 2)
            ElseIf posDlmtr <= 0 Then
                canLoop = False
            End If
        Loop
        strText.Trim()
        MsgBox(strText)
To provide perspective the script is meant to take a string like "Gui, Add, Text, vhi ghi, Hello" and extract Hello out of it by looping the creation of a substring at the position of InStr(", ") and for the length of str.length - InStr(", ") .

Can anyone provide insight on this?
 
Your order of operations is off....
Specificaly in the legth parameter of the substring....
intTextLen - posDlmtr + 2
On the first time through:
intTextLen = 30
posDlmtr = 4
So it comes out with a value of
30 - 4 + 2 or 28.... which is too long....
When I added parenthesis to it, like this:
intTextLen - (posDlmtr + 2)
It became more correct... but I got "ello"....
So I changed the 2's to 1's.... like this:
VB.NET:
strText = strText.Substring(posDlmtr + 1, intTextLen - (posDlmtr + 1))
And it now returns "Hello" like it should.

-tg
 
Back
Top