简体   繁体   中英

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??

This may be dialect dependent, so try the following

'Smalltalk' includesSubstring: 'mall' --> true
'Smalltalk' includesSubstring: 'malta' --> true

'Smalltalk' indexOfSubCollection: 'mall' --> 2
'Smalltalk' indexOfSubCollection: 'malta' --> 0

(see Bob's comment below)

'Smalltalk' indexOfSubCollection: 'mall' startingAt: 1 --> 2
'Smalltalk' indexOfSubCollection: 'malta' startingAt: 1 --> 0

You may want to add one of the above to your image eg

String >> includesString: aString
  ^(self indexOfSubCollection: aString: startingAt: 1) > 0

Match works fine in VisualWorks, but I add a utility method to string:

includesSubString: aString

| readStream |
readStream := self readStream.
readStream upToAll: aString.
^readStream atEnd not

try #match: , like so: '*fox*' match: 'there''sa fox in the woods' . There're two kinds of wildcards: * and # . # matches any single character. * matches any number of characters (including none).

#match: defaults to case-insensitive matching, if you need case-sensitive, use #match:ignoringCase: and pass false as second argument.

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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM