问题
Given an array of NSStrings which have several repeated copies:
AAA
BBB
AAA
AAA
BBB
BBB
BBB
BBB
CCC
What's the easiest way to get the string which is most occurring?
回答1:
Use NSCountedSet and then find the largest 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;
}
}
Checking the result:
NSLog(@"Most frequent string: %@", mostOccurring);
来源:https://stackoverflow.com/questions/11140989/get-most-occurring-nsstring-in-an-array