在数组中查找最重复的对象

编程入门 行业动态 更新时间:2024-10-28 06:34:57
本文介绍了在数组中查找最重复的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个充满字符串的数组,每个字符串都是一个名字。有些名称可能相同,有些名称可能不同。我正在使用的语言是Objective-C。我希望能够从这个数组中找出最受欢迎的名称(该数组将根据用户提供给应用程序的信息而动态显示)。我不确定如何有效地实现这一目标。如果有人可以扩展或提供一个例子,我们将不胜感激。

I have an array full of strings with each string being a name. Some names may be the same while some may be different. The language I'm working in is objective-C. I want to be able to find out which name is most popular from this array (the array will be dynamic based on information given to the app from the user). I am not sure how to make this happen EFFICIENTLY. If someone could expand on this or provide an example, it would be appreciated.

谢谢

示例:

NSArray *nameArray= [[NSArray alloc] initWithObjects @"james", @"megan", @"lauren", @"mike" @james", nil]; //james would be the most popular name

推荐答案

使用 NSCountedSet ,然后使用 countForObject:方法找到计数最高的对象。

Use NSCountedSet and then find the object with highest count using countForObject: method.

//create count set from array NSCountedSet *setOfObjects = [[NSCountedSet alloc] initWithArray:yourArrayhere]; //Declaration of objects NSString *mostOccurringObject = @""; NSUInteger highestCount = 0; //Iterate in set to find highest count for a object for (NSString *strObject in setOfObjects) { NSUInteger tempCount = [setOfObjects countForObject:strObject]; if (tempCount > highest) { highestCount = tempCount; mostOccurringObject = strObject; } }

检查结果:

NSLog(@"Most frequent string: %@ with count: %i", mostOccurringObject,highestCount);

信用转到 @ Evan Mulawski 回答

更多推荐

在数组中查找最重复的对象

本文发布于:2023-11-22 00:56:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1615344.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!