在数组中获取最多的NSString

给定一个有几个重复副本的NSString数组:

 AAA BBB AAA AAA BBB BBB BBB BBB CCC 

获取最多发生的string的最简单方法是什么?

使用NSCountedSet ,然后find最大的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);