Objective-C:-[NSString wordCount]
以下 NSString
类别方法的简单实现是什么,该方法返回 self 中的单词数,其中单词由任意数量的连续空格或换行符分隔?此外,该字符串将少于 140 个字符,因此在这种情况下,我更喜欢简单性和简单性。牺牲一点性能来提高可读性。
@interface NSString (Additions)
- (NSUInteger)wordCount;
@end
我找到了以下解决方案:
- -[NSString wordCount] 的实现
- -[NSString wordCount] 的实现 - 似乎更简单
但是,有没有更简单的方法?
What's a simple implementation of the following NSString
category method that returns the number of words in self
, where words are separated by any number of consecutive spaces or newline characters? Also, the string will be less than 140 characters, so in this case, I prefer simplicity & readability at the sacrifice of a bit of performance.
@interface NSString (Additions)
- (NSUInteger)wordCount;
@end
I found the following solutions:
- implementation of -[NSString wordCount]
- implementation of -[NSString wordCount] - seems a bit simpler
But, isn't there a simpler way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
为什么不直接执行以下操作呢?
Why not just do the following?
我相信你已经确定了“最简单”的。尽管如此,为了回答您最初的问题 - “以下 NSString 类别 的简单实现...”,并将其直接发布在这里以供后代使用:
I believe you have identified the 'simplest'. Nevertheless, to answer to your original question - "a simple implementation of the following NSString category...", and have it posted directly here for posterity:
有许多更简单的实现,但它们都有权衡。例如,Cocoa(但不是 Cocoa Touch)内置了字数统计功能:
只需使用
[[self ComponentsSeparatedByCharactersInSet:[NSCharacterSet WhitespaceAndNewlineCharacterSet]] count]
即可像扫描仪一样准确地统计字数。但我发现对于较长的字符串,该方法的性能会下降很多。所以这取决于您想要做出的权衡。我发现绝对最快的方法就是直接进入ICU。如果您想要最简单,那么使用现有代码可能比编写任何代码更简单。
There are a number of simpler implementations, but they all have tradeoffs. For example, Cocoa (but not Cocoa Touch) has word-counting baked in:
It's also trivial to count words as accurately as the scanner simply using
[[self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] count]
. But I've found the performance of that method degrades a lot for longer strings.So it depends on the tradeoffs you want to make. I've found the absolute fastest is just to go straight-up ICU. If you want simplest, using existing code is probably simpler than writing any code at all.
看起来我在问题中给出的第二个链接仍然占据主导地位,不仅是最快的,而且事后看来,也是一个相对简单的 -[NSString wordCount] 的实现。
Looks like the second link I gave in my question still reigns as not only the fastest but also, in hindsight, a relatively simple implementation of -[NSString wordCount].
Objective-C 单行版本
A Objective-C one-liner version
斯威夫特3:
Swift 3: