Objective-C:如何找到数组中最常见的字符串? [英] Objective-C: How to find the most common string in an array?

查看:79
本文介绍了Objective-C:如何找到数组中最常见的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在线数据库中的字符串数组,试图确定最常用的单词.数组中的值会有所不同,但是我想检查任何集合或使用的单词中最常见的单词.从理论上讲,如果我有以下数组...

I have an array of strings from an online database that I trying to determine the most commonly used word. The values inside the arrays will vary but I want to check the most common words of whatever collection or words I'm using. If theoretically I had an array of the following...

NSArray *stringArray = [NSArray arrayWithObjects:@"Duck", @"Duck", @"Duck", @"Duck", @"Goose"];

如何遍历此数组以确定最常见的字符串(显然是"Duck")?

How do I iterate through this array to determine the most common string, which would obviously be "Duck"?

推荐答案

最简单的方法可能是NSCountedSet:

NSCountedSet* stringSet = [[NSCountedSet alloc] initWithArray:strings];
NSString* mostCommon = nil;
NSUInteger highestCount = 0;

for(NSString* string in stringSet) {
    NSUInteger count = [stringSet countForObject:string];
    if(count > highestCount) {
        highestCount = count;
        mostCommon = string;
    }
}

这篇关于Objective-C:如何找到数组中最常见的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆