visualworks smalltalk:如何从字符串中检测子字符串,这可能吗?

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

如标题所示,我不确定检测字符串中是否存在子字符串的最佳途径,例如:

OverExtended:anErrorMessage

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

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

现在我知道上面的方法行不通了,但是现在有检查子字符串的方法吗??

这可能与方言有关,因此请尝试以下操作

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

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

(见下面 Bob 的评论)

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

您可能希望将以上内容之一添加到您的图片中,例如

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

尝试 #match:,像这样:'*fox*' match: 'there''s a fox in the woods'。有两种通配符:*## 匹配任何单个字符。 * 匹配任意数量的字符(包括 none)。

#match:默认不区分大小写匹配,如果需要区分大小写,使用#match:ignoringCase:并传递false作为第二个参数。

Match 在 VisualWorks 中运行良好,但我向字符串添加了一个实用方法:

包括子字符串:aString

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

我找到了一个在所有情况下既简单又准确的答案 w/o 对 readStreams 的依赖或对 'naitive' VW 的扩展,最早可追溯到 VW7.4:

只需使用 findString:startingAt: 并对出现次数进行大于零的检查

示例:

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