iOS - 在字符串中查找单词出现次数的最有效方法

RyJ*_*RyJ 12 objective-c nsstring nsset ios

给定一个字符串,我需要获得该字符串中出现的每个单词的计数.为此,我通过单词将字符串提取为数组,然后以这种方式进行搜索,但我觉得直接搜索字符串更为理想.下面是我最初编写的用于解决问题的代码.我想提出更好的解决方案的建议.

NSMutableDictionary *sets = [[NSMutableDictionary alloc] init];

NSString *paragraph = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"text" ofType:@"txt"] encoding:NSUTF8StringEncoding error:NULL];

NSMutableArray *words = [[[paragraph lowercaseString] componentsSeparatedByString:@" "] mutableCopy];

while (words.count) {
    NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init];
    NSString *search = [words objectAtIndex:0];
    for (unsigned i = 0; i < words.count; i++) {
        if ([[words objectAtIndex:i] isEqualToString:search]) {
            [indexSet addIndex:i];
        }
    }
    [sets setObject:[NSNumber numberWithInt:indexSet.count] forKey:search];
    [words removeObjectsAtIndexes:indexSet];
}

NSLog(@"%@", sets);
Run Code Online (Sandbox Code Playgroud)

例:

起始字符串:
"这是一个测试.这只是一个测试."

结果:

  • "这个" - 2
  • "是" - 2
  • "a2
  • "测试" - 2
  • "只有1个

lna*_*ger 24

这正是NSCountedSet它的用途.

你需要将字符串拆分成单词(iOS足够好以便为我们提供一个函数,以便我们不必担心标点符号)并将它们中的每一个添加到计数集中,这会跟踪数字每个对象出现在集合中的次数:

NSString     *string     = @"This is a test. This is only a test.";
NSCountedSet *countedSet = [NSCountedSet new];

[string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                           options:NSStringEnumerationByWords | NSStringEnumerationLocalized
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop){

                            // This block is called once for each word in the string.
                            [countedSet addObject:substring];

                            // If you want to ignore case, so that "this" and "This" 
                            // are counted the same, use this line instead to convert
                            // each word to lowercase first:
                            // [countedSet addObject:[substring lowercaseString]];
                        }];

NSLog(@"%@", countedSet);

// Results:  2012-11-13 14:01:10.567 Testing App[35767:fb03] 
// <NSCountedSet: 0x885df70> (a [2], only [1], test [2], This [2], is [2])
Run Code Online (Sandbox Code Playgroud)