Objective-C的:数出数组中出现的对象的次数? [英] Objective-C: Count the number of times an object occurs in an array?

查看:105
本文介绍了Objective-C的:数出数组中出现的对象的次数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行什么,我觉得是一个基本的功能,但我无法找到如何做的文档。请帮助!

I need to perform what I feel is a basic function but I can't find any documentation on how to do it. Please help!

我需要计数某个对象以阵列多少次发生。见例如:

I need to count how many times a certain object occurs in an array. See example:

array = NSArray arrayWithObjects:@"Apple", @"Banana", @"Cantaloupe", @"Apple", @"DragonFruit", @"Eggplant", @"Apple", @"Apple", @"Guava",nil]retain];

如何通过遍历数组和计数的次数就找到字符串@苹果?

How can I iterate through the array and count the number of times it finds the string @"Apple"?

任何帮助AP preciated!

Any help is appreciated!

推荐答案

一个简单而明确的答案:

A Simple and specific answer:

int occurrences = 0;
for(NSString *string in array){
    occurrences += ([string isEqualToString:@"Apple"]?1:0); //certain object is @"Apple"
}
NSLog(@"number of occurences %d", occurrences);

PS:马丁Babacaev的答案是相当不错了。迭代更快地块,但与我猜没有明显的增益,使几个要素这种特殊情况下。我会用,虽然:)

PS: Martin Babacaev's answer is quite good too. Iteration is faster with blocks but in this specific case with so few elements I guess there is no apparent gain. I would use that though :)

这篇关于Objective-C的:数出数组中出现的对象的次数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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