Quantcast
Channel: VBForums - CodeBank - Visual Basic 6 and earlier
Viewing all articles
Browse latest Browse all 1448

[VB6] Extended InStr-Function

$
0
0
Here's a small function i use extensively when parsing strings.
Arguments:
Source = The string to search in
Delimiters = The single Delimiters as a String we're searching for
LeftToRight = The Direction of the Search
DelChar = Out-Parameter returning the found delimiter

The Result is the position of whichever Delimiter has been found first

The difference to the "native" InStr-Function is, that in case of e.g.
InStr(1,"SomeSource@Domain.Com","@.")
the native InStr would search for the complete (sub-) string of "@." instead of whichever of the two delimiters appears first

Code:

Public Function InStrSet(ByVal Source As String, _
                        ByVal Delimiters As String, _
                        Optional ByVal LeftToRight As Boolean = True, _
                        Optional ByRef DelChar As String = vbNullString) As Long
Dim i As Long
Dim j As Long
Dim o As Long
Dim x As Long
Dim t As String
    InStrSet = 0                                        'Initialize to failure
    DelChar = vbNullString                              'In case a character is passed through
    If Len(Source) = 0 Or Len(Delimiters) = 0 Then      'err....yes, well.....
        Exit Function
    End If
    If LeftToRight Then                                'Are we searching from the start?
        t = Source
        o = 0
        x = -1
    Else                                                'or are we searching from the end?
        t = StrReverse(Source)
        o = Len(t) + 1                                  'Offset
        x = 1
    End If
    If Len(Delimiters) = 1 Then                        'If only 1 Delimiter use native InStr
        j = InStr(1, t, Delimiters)
        If j > 0 Then
            InStrSet = o - x * j
            DelChar = Delimiters
        End If
    Else
        For i = 1 To Len(t)                            'Run through the Scource character-wise
            j = InStr(1, Delimiters, Mid$(t, i, 1))    'Check Source-Character if it's in Delimiter-String
            If j > 0 Then                              'If found
                InStrSet = o - x * i                    'set Result to current Source-Character
                DelChar = Mid$(Delimiters, j, 1)        'set DelChar to which Delimiter was found
                Exit For
            End If
        Next
    End If
End Function


Viewing all articles
Browse latest Browse all 1448

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>