Search code examples
stringsubstringsmalltalkvisualworks

visualworks smalltalk: how can I detect substring from a string, is it possible?


as title suggests I'm not sure best route to detect the presence of a substring in a string, for example:

OverExtended:anErrorMessage

"anErrorMessage = 'error: robot arm extended too far' "

(anErrorMessage **contains:** 'extended too far')
ifTrue:[
   ...
   ...
]
ifFalse:[
   ...
   ...
].

Now I know the above doesnt work, but is there an existing method for checking for substrings??


Solution

  • I have found an answer that is both simple and accurate in all scenarios w/o dependancy on readStreams or extentions to 'naitive' VW as far back as VW7.4:

    simply use findString:startingAt: and do a greater then zero check for # of occurences

    sample:

    |string substring1 substring2|
    string:= 'The Quick Brown Fox'.
    substring1:= 'quick'.
    substring2:='Quick'.
    
    "below returns FALSE as 'quick' isnt found"
    (string findString: substring1 startingAt:1)>0
    ifTrue:[^'found [quick]'].
    
    "below returns TRUE as 'Quick' is found"
    (string findString: substring2 startingAt:1)>0
    ifTrue:[^'found [Quick]'].
    
    ^'found nothing'.