NSString
给定一个包含多个重复副本的 s 数组:
AAA
BBB
AAA
AAA
BBB
BBB
BBB
BBB
CCC
获取最常出现的字符串的最简单方法是什么?
NSString
给定一个包含多个重复副本的 s 数组:
AAA
BBB
AAA
AAA
BBB
BBB
BBB
BBB
CCC
获取最常出现的字符串的最简单方法是什么?
使用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);