得到最存在的NSString在阵列中(Get most-occurring NSString in

2019-09-18 08:14发布

鉴于阵列NSString S的有几个重复的副本:

AAA
BBB
AAA
AAA
BBB
BBB
BBB
BBB
CCC

什么是得到被大多数发生的字符串的最简单的方法?

Answer 1:

使用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);


文章来源: Get most-occurring NSString in an array