Objective-C: -[NSString wordCount]

后端 未结 7 1206
孤街浪徒
孤街浪徒 2020-12-05 21:39

What\'s a simple implementation of the following NSString category method that returns the number of words in self, where words are separated by an

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 22:01

    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];
    }
    

提交回复
热议问题