在数组中获取最常出现的NSString

时间:2012-06-21 15:00:48

标签: objective-c ios arrays nsstring

给定一组NSString s,它有几个重复的副本:

AAA
BBB
AAA
AAA
BBB
BBB
BBB
BBB
CCC

获取最常出现的字符串的最简单方法是什么?

1 个答案:

答案 0 :(得分:7)

使用NSCountedSet,然后找到最大的countForObject:

NSCountedSet *bag = [[NSCountedSet alloc] initWithArray:myArray];

NSString *mostOccurring;
NSUInteger highest = 0;
for (NSString *s in bag)
{
    if ([bag countForObject:s] > highest)
    {
        highest = [bag countForObject:s];
        mostOccurring = s;
    }
}

检查结果:

NSLog(@"Most frequent string: %@", mostOccurring);