Get the most common NSString in an array

Given an array NSStringthat has multiple duplicate copies:

AAA
BBB
AAA
AAA
BBB
BBB
BBB
BBB
CCC

What is the easiest way to get the string that is most found?

+2
source share
1 answer

Use NSCountedSetand 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;
    }
}

Verification of the result:

NSLog(@"Most frequent string: %@", mostOccurring);
+7
source

All Articles