Get most-occurring NSString in an array

纵然是瞬间 提交于 2019-12-11 03:11:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!