Jump to content

UDF: _StringInSet


blindwig
 Share

Recommended Posts

I got tired of doing this:

If $i = 1 or $i = 3 or $i = 7 or $i = 12 ...

so I write a function to work like this:

If _StringInSet($i, '1,3,7,12,...')

And here it is:

CODE

Func _StringInSet($Value, $List, $Delim=',')

Dim $Result=0, $ListArray, $i

$ListArray=StringSplit($List,$Delim)

$i = 1

While $i<=$ListArray[0] And Not $Result

If $Value=$ListArray[$i] Then $Result=-1

$i = $i + 1

WEnd

Return $Result

EndFunc

It's smarter than just using StringInStr because it won't match partials.

Link to comment
Share on other sites

Hi blindwig,

Yes, good idea. A good UDF, can save some extra typing.

I would have done it a little different.

Func _StringInSetOr($Value, $List, $Delim = '|')
    Dim $ListArray=StringSplit($List,$Delim)
    If @error Then Return 0
    For $i = 1 To $ListArray[0]
        If $Value = $ListArray[$i] Then Return 1
    Next
EndFunc

I try to avoid using comma's as delimiters. I have learnt my lesson with other languages, in the past. Accidently typing a period, somewhere in the string, makes fun debugging. But it is good that you chose as optional.

Or this is with error return

Func _StringInSetOr($Value, $List, $Delim = '|')
    Dim $ListArray=StringSplit($List,$Delim)
    If @error Then
        SetError(1)
        Return 0
    EndIf
    For $i = 1 To $ListArray[0]
        If $Value = $ListArray[$i] Then Return 1
    Next
EndFunc
Edited by MHz
Link to comment
Share on other sites

  • 3 years later...

This is a very old thread, I know.

However this is my way doing it ...

Func StringInSet( $str, $set, $delim="|" );Tests wether string is in set of strings. Returns item no of str in set if found, 0 if not.
    $set= $delim & $set & $delim
    Local $res= StringInStr($set, $delim & $str & $delim)
    If $res>0 Then
        StringReplace( StringLeft($set,$res), $delim, " " )
        Return @extended    ;return replacement count (=item no)
    EndIf
    Return 0
EndFunc
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...