Objective-C:-[NSString wordCount]

发布于 2024-11-10 12:55:12 字数 513 浏览 4 评论 0原文

以下 NSString 类别方法的简单实现是什么,该方法返回 self 中的单词数,其中单词由任意数量的连续空格或换行符分隔?此外,该字符串将少于 140 个字符,因此在这种情况下,我更喜欢简单性和简单性。牺牲一点性能来提高可读性。

@interface NSString (Additions)
- (NSUInteger)wordCount;
@end

我找到了以下解决方案:

但是,有没有更简单的方法?

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:

But, isn't there a simpler way?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

坦然微笑 2024-11-17 12:55:12

为什么不直接执行以下操作呢?

- (NSUInteger)wordCount {
    NSCharacterSet *separators = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSArray *words = [self componentsSeparatedByCharactersInSet:separators];

    NSIndexSet *separatorIndexes = [words indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isEqualToString:@""];
    }];

    return [words count] - [separatorIndexes count];
}

Why not just do the following?

- (NSUInteger)wordCount {
    NSCharacterSet *separators = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSArray *words = [self componentsSeparatedByCharactersInSet:separators];

    NSIndexSet *separatorIndexes = [words indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isEqualToString:@""];
    }];

    return [words count] - [separatorIndexes count];
}
女中豪杰 2024-11-17 12:55:12

我相信你已经确定了“最简单”的。尽管如此,为了回答您最初的问题 - “以下 NSString 类别 的简单实现...”,并将其直接发布在这里以供后代使用:

@implementation NSString (GSBString)

- (NSUInteger)wordCount
{
    __block int words = 0;
    [self enumerateSubstringsInRange:NSMakeRange(0,self.length)
                             options:NSStringEnumerationByWords
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {words++;}];
    return words;
}

@end

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:

@implementation NSString (GSBString)

- (NSUInteger)wordCount
{
    __block int words = 0;
    [self enumerateSubstringsInRange:NSMakeRange(0,self.length)
                             options:NSStringEnumerationByWords
                          usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {words++;}];
    return words;
}

@end
魔法唧唧 2024-11-17 12:55:12

有许多更简单的实现,但它们都有权衡。例如,Cocoa(但不是 Cocoa Touch)内置了字数统计功能:

- (NSUInteger)wordCount {
    return [[NSSpellChecker sharedSpellChecker] countWordsInString:self language:nil];
}

只需使用 [[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:

- (NSUInteger)wordCount {
    return [[NSSpellChecker sharedSpellChecker] countWordsInString:self language:nil];
}

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.

长伴 2024-11-17 12:55:12
- (NSUInteger) wordCount
{
   NSArray *words = [self componentsSeparatedByString:@" "];
   return [words count];
}
- (NSUInteger) wordCount
{
   NSArray *words = [self componentsSeparatedByString:@" "];
   return [words count];
}
淡莣 2024-11-17 12:55:12

看起来我在问题中给出的第二个链接仍然占据主导地位,不仅是最快的,而且事后看来,也是一个相对简单的 -[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].

So尛奶瓶 2024-11-17 12:55:12

Objective-C 单行版本

NSInteger wordCount = word ? ([word stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet.invertedSet].length + 1) : 0;

A Objective-C one-liner version

NSInteger wordCount = word ? ([word stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet.invertedSet].length + 1) : 0;
甜心 2024-11-17 12:55:12

斯威夫特3:

let words: [Any] = (string.components(separatedBy: " "))
let count = words.count

Swift 3:

let words: [Any] = (string.components(separatedBy: " "))
let count = words.count
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文