给定一组NSString
s,它有几个重复的副本:
AAA
BBB
AAA
AAA
BBB
BBB
BBB
BBB
CCC
获取最常出现的字符串的最简单方法是什么?
答案 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);