Objective-C:如何在数组中找到最常见的字符串?

时间:2014-06-28 02:36:25

标签: objective-c nsstring nsarray

我有一个来自在线数据库的字符串数组,我试图确定最常用的单词。数组内部的值会有所不同,但我想查看我使用的任何集合或单词中最常见的单词。如果理论上我有以下数组...

NSArray *stringArray = [NSArray arrayWithObjects:@"Duck", @"Duck", @"Duck", @"Duck", @"Goose"];

如何遍历此数组以确定最常见的字符串,这显然是" Duck"?

3 个答案:

答案 0 :(得分:10)

最简单的方法可能是NSCountedSet

NSCountedSet* stringSet = [[NSCountedSet alloc] initWithArray:strings];
NSString* mostCommon = nil;
NSUInteger highestCount = 0;

for(NSString* string in stringSet) {
    NSUInteger count = [stringSet countForObject:string];
    if(count > highestCount) {
        highestCount = count;
        mostCommon = string;
    }
}

答案 1 :(得分:3)

您可以将该词用作词典中的键。

NSMutableDictionary *words = [NSMutableDictionary dictionary];
for (NSString *word in stringArray) {
    if (!words[word]) {
        [words setValue:[NSDecimalNumber zero] forKey:word];
    }

    words[word] = [words[word] decimalNumberByAdding:[NSDecimalNumber one]];
}

现在遍历words并找到具有最高值的密钥。

NSString *mostCommon;
NSDecimalNumber *curMax = [NSDecimalNumber zero];
for (NSString *key in [words allKeys]) {
    if ([words[key] compare:curMax] == NSOrderedDescending) {
        mostCommon = key;
        curMax = word[key];
    }
}

NSLog(@"Most Common Word: %@", mostCommon);

编辑:而不是循环遍历数组,然后通过排序字典单独循环,我认为我们可以做得更好,并在一个循环中完成所有操作。

NSString *mostCommon;
NSDecimalNumber *curMax = [NSDecimalNumber zero];
NSMutableDictionary *words = [NSMutableDictionary dictionary];
for (NSString *word in stringArray) {
    if (!words[word]) {
        [words setValue:[NSDecimalNumber zero] forKey:word];
    }

    words[word] = [words[word] decimalNumberByAdding:[NSDecimalNumber one]];

    if ([words[word] compare:curMax] == NSOrderedDescending) {
        mostCommon = word;
        curMax = words[word];
    }
}

NSLog(@"Most Common Word: %@", mostCommon);

这应该明显快于我的预编辑答案,但我不知道它与使用NSCountedSet答案相比如何。

答案 2 :(得分:1)

尝试使用NSPredicate。

NSUInteger count=0;
NSString *mostCommonStr;
for(NSString *strValue in stringArray) {
   NSUInteger countStr=[[stringArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self MATCHES[CD] %@, strValue]]count];
   if(countStr > count) {
       count=countStr;
       mostCommonStr=strValue;
   }
}
NSLog(@"The most commonstr is %@",mostCommonStr);