How to count duplicates values in NSArray?

核能气质少年 提交于 2019-12-03 05:18:09

问题


Value of my NSArray includes the duplicates. I find the duplicates but now how can I find the no. they repeat?


回答1:


You can use NSCountedSet for this. Add all your objects to a counted set, then use the countForObject: method to find out how often each object appears.




回答2:


Example:

NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John", nil];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];

for (id item in set) {

    NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
}



回答3:


You can try something like this

__block NSInteger elementCount = 0;
NSArray *array;

[<#NSArray yourArray#> indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop){
    if (obj == <#yourObject#>) {
        elementCount++;
        return YES;
    }
    return NO;
}];

Let me know if that works for you



来源:https://stackoverflow.com/questions/6841072/how-to-count-duplicates-values-in-nsarray

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