Link to home
Start Free TrialLog in
Avatar of guava070998
guava070998

asked on

strtok function

I would like a function to do the same as the strtok function under C.  It should take a variable number of tokens (characters, could all be in one string just like strtok) to tokenize on.   Each token should be a string.

eg:

' Tokenize based on command ',' and space ' '
strtok("Have      a  nice,     day", " ,")

This should break the above string into :
"Have"
"a"
"nice"
"day"

Thanks for any help
Guava
ASKER CERTIFIED SOLUTION
Avatar of anthonyc
anthonyc

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of tomook
tomook

anthonyc, that really does not mimic strtok. Here is one that does, including using static variables.

' Tokenize a string like 'strtok' in C std lib
' Does not modify source string like strtok.
Function StrTok(Seps As String, Optional SourceString As Variant) As String
    Static LocalString As String
    Static LocalCounter As Long     ' Substitutes for pointer into string
    Dim lCnt1 As Long

    If Not (IsMissing(SourceString)) Then
        LocalString = SourceString
        LocalCounter = 1    ' Must start at first char.
    End If
   
    ' If we start on a separator, skip all seps found.
    While (LocalCounter <= Len(LocalString)) And (InStr(Seps, Mid$(LocalString, LocalCounter, 1))) <> 0
        LocalCounter = LocalCounter + 1
    Wend
   
    '
    lCnt1 = LocalCounter
   
    ' Count until separators found.
    While (lCnt1 <= Len(LocalString)) And (InStr(Seps, Mid$(LocalString, lCnt1, 1)) = 0)
        lCnt1 = lCnt1 + 1
    Wend
       
    StrTok = Mid$(LocalString, LocalCounter, lCnt1 - LocalCounter)
   
    ' LocalCounter must point to next char to examine
    LocalCounter = lCnt1 + 1
End Function

Yeah, you are right.. It's an enhanced version.  You get all of the tokens returned in 1 pass, in 1 array.
Yeah, I noticed that. I guess it depends on what you are looking for. In writing VB parsers, I usually need to change the separators so I use the version I posted.
Avatar of guava070998

ASKER

Hi, thanks for the quick replies.  I will try this out as soon as possible and get back to you both on if either suits what I happen to need.

Thanks again,
guava
Hi, I tried both, both work, and I like both....so, what do we do about the points here?  Technically the second example mimics strtok more, which I asked for...but the first code actually require me to do a wee less work....

How would you both feel about getting this question archived, my points returned, and I ask two 40 point questions, one for each of you, just to pick up the points? (ie: you would just have to offically answer the question, now actual work involved since you answered this one).

Does that sound good, or should I just decide which code does my job better and answer?

guava
guava,

Anything is fine with me
I am easy.