繁体   English   中英

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

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

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

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

(见下面鲍勃的评论)

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

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

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

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

包括子字符串:一个字符串

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

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

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

我找到了一个在所有场景中既简单又准确的答案,不依赖于 readStreams 或早在 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'.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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