丢弃集合中元素之前的元素的最佳方法
给定任何像“Lorem ipsum dolor sat amet, consectetuer adipiscing elit”这样的字符串,我想在“sit”之前丢弃每个单词。我检查了 String 中的方法,但没有发现对此非常有用。这是我的尝试:
| phrase newPhrase |
phrase := 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit'.
newPhrase := phrase substrings.
phrase substrings do: [: word | word = 'sit' ifFalse: [ newPhrase := newPhrase allButFirst ] ifTrue: [ ^ nil ] ].
newPhrase joinUsing: String space
在工作区中评估时它回答为零,但是必须有一个聪明的方法,对吗?
Given any String like 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit' I'd like to discard every word before sit. I've checked methods in String but not found very useful for this one. This is my try:
| phrase newPhrase |
phrase := 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit'.
newPhrase := phrase substrings.
phrase substrings do: [: word | word = 'sit' ifFalse: [ newPhrase := newPhrase allButFirst ] ifTrue: [ ^ nil ] ].
newPhrase joinUsing: String space
it is answering nil when evaluated in a Workspace and however there must be a clever way right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代码:
当找到单词 sit 时,返回 nil。
请注意,Smalltalk 中的 ^ 始终从封闭方法返回。它不会突破
do:
。试试这个
丢弃 sit 之前的所有单词:
您可能还会发现这些收集方法很有趣:
The code:
returns nil when the word sit is found.
Note that ^ in Smalltalk always return from the enclosing method. It doesn't break out of the
do:
.Try this instead
To discard all words before sit:
You may also find these collection methods interesting:
我会同意亚历山大的第一个答案:
它似乎比以下任何一种都更能揭示意图(即清晰),但只是为了好玩,这里还有另外两种方法:
如果在分析之后,您想要更高的效率。这种方式的效率提高了 25 倍:
PetitParser:效率降低了 10 倍,但在更复杂的解析情况下,这是一个可以放在口袋里的好工具:
此外,您必须决定如果没有找到“sit”该怎么办。
I would go with Alexandre's first answer:
It seems more intention revealing (i.e. clear) than either of the following, but just for fun, here's two other ways:
If, after profiling, you wanted more efficiency. This way is 25 times more efficient:
PetitParser: 10 times less efficient, but a great tool to have in your pocket in more complex parsing situations:
Also, you have to decide what to do if 'sit' is not found.