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

查看:28
本文介绍了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];

如何遍历数组并计算它找到字符串@"Apple"的次数?

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

感谢任何帮助!

推荐答案

一个简单而具体的答案:

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:Martin 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天全站免登陆