簡體   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