INSTR issue with negative direction and nth direction
issueid=350 17-03-2012 19:03
Super Moderator
Number of reported issues by Petr Schreiber: 162
INSTR issue with negative direction and nth direction
Incorrect results are given in case of negative direction search in conjunction with nthOccurrence parameter

Originaly reported by Klaus Heinz here:

Fiddling around with INSTR I encountered a bug regarding right to left searching.
Following program shows that the nth occurrence of "+" found at its correct position
searching from left to right. Doing this from right to left it just fails.
But may be I am missing something.

Klaus Heinz

Uses "Console" 
' string with plus character at indexes 5, 10, 15 and 20
Dim test$ Value "----+----+----+----+"
' find from first index to right 
PrintL "Expect  5, get", InStr(1, test$, "+", 1)
PrintL "Expect 10, get", InStr(1, test$, "+", 2)
PrintL "Expect 15, get", InStr(1, test$, "+", 3) 
PrintL "Expect 20, get", InStr(1, test$, "+", 4) 
' find from last index to left
PrintL "Expect 20, get", InStr(-1, test$, "+", 1)
PrintL "Expect 15, get", InStr(-1, test$, "+", 2)
PrintL "Expect 10, get", InStr(-1, test$, "+", 3) 
PrintL "Expect  5, get", InStr(-1, test$, "+", 4) 
Issue Details
Issue Number 350
Project thinBasic
Category Core engine (thinCore.dll)
Status Fixed
Priority 2
Affected Version 1.8.9
Fixed Version 1.9.1
Milestone thinBasic
Users able to reproduce bug 1
Users unable to reproduce bug 0
Assigned Users (none)
Tags (none)

17-03-2012 19:19
Super Moderator
Hot fix in the meantime:
Function INSTR_Fixed(startPosition As Long, sMainString As String, sMatchString As String, Optional nthOccurence As Long = 1) As Long
  Long positionFound
  If startPosition < 0 Then
    Long i
    Long lMain = Len(sMainString)             

    For i = 1 To nthOccurence   
      positionFound = InStr(IIf(i = 1, startPosition, -1), sMainString, sMatchString) 
      If positionFound Then
        sMainString = LEFT$(sMainString, positionFound-1)
        Exit For 
      End If 
    Return positionFound
    Return InStr(startPosition, sMainString, sMatchString, nthOccurence)
  End If
End Function

18-03-2012 10:55
thinBasic author
Attached (at the very bottom of this thread) a possible temporary fix until thinBasic 1.9 will be out.

How to install
thinCore.Zip contains thinCore.dll
Copy (replacing your current one) thinCore.dll into \thinBasic\ directory.

+ Reply