[英]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:正如标题所示,我不确定检测字符串中是否存在 substring 的最佳途径,例如:
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: Match 在 VisualWorks 中运行良好,但我在字符串中添加了一个实用方法:
includesSubString: aString包括子字符串:一个字符串
| readStream |
readStream := self readStream.
readStream upToAll: aString.
^readStream atEnd not
try #match:
, like so: '*fox*' match: 'there''sa fox in the woods'
.试试
#match:
,就像这样: '*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. #match:
默认为不区分大小写的匹配,如果需要区分大小写,请使用#match:ignoringCase:
并传递false
作为第二个参数。
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:我找到了一个在所有场景中既简单又准确的答案,不依赖于 readStreams 或早在 VW7.4 的“原始”大众汽车的扩展:
simply use findString:startingAt: and do a greater then zero check for # of occurences只需使用findString:startingAt:并对出现次数进行大于零的检查
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'.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.