2

NSString给定一个包含多个重复副本的 s 数组:

AAA
BBB
AAA
AAA
BBB
BBB
BBB
BBB
CCC

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

4

1 回答 1

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);
于 2012-06-21T15:14:13.600 回答