从iOS中的数组中获取重复项以及原始项

时间:2017-05-05 06:41:02

标签: ios objective-c arrays nscountedset

我有一个数组,如

(约翰,简,约翰)

我想获得重复项,以及像

这样的数组的原始元素

(约翰,约翰) 我能够从代码中获得单一的出现 这里

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]);
    if((unsigned long)[set countForObject:item]>1){
        NSLog(@"of repeated element-----=%@",item);
    }
} 

"重复元素的名称----- John"但是我希望所有出现的重复元素如#34;重复元素的名称----- John,John"

3 个答案:

答案 0 :(得分:1)

试试这个使用NSPredicate

NSArray *array = [NSArray arrayWithObjects:@"John", @"Jane", @"John",@"Jane",@"Jane", nil];
NSMutableArray *arrResult = [[NSMutableArray alloc] init];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:array];
for(id name in set)
   {
        if([set countForObject:name] > 1 ){
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF = %@", name];
            [arrResult addObjectsFromArray:[array filteredArrayUsingPredicate:predicate]];
        }
    }
    //
    NSLog(@"%@",arrResult);

答案 1 :(得分:0)

我不确定你的最终目的,你想要的结果看起来毫无意义。无论如何,出于研究目的,以下是一个实现;)

NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John", nil];

NSMutableDictionary *countDict = [NSMutableDictionary dictionary];
for (NSString *name in names) {
    if (countDict[name] == nil) {
        countDict[name] = [NSMutableString stringWithString:name];
    }
    else{
        NSMutableString *repeatedName = (NSMutableString *)countDict[name];
        [repeatedName appendString:@","];
        [repeatedName appendString:name];
    }
}
[countDict enumerateKeysAndObjectsUsingBlock:^(NSString *_Nonnull name, NSString * _Nonnull repeatedNames, BOOL * _Nonnull stop) {
    if (repeatedNames.length > name.length) {
        NSLog(@"Name of repeated element-----%@",repeatedNames);
    }
}];

输出:重复元素的名称----- John,John

答案 2 :(得分:0)

使用loop

尝试此代码
NSArray *names = [NSArray arrayWithObjects:@"John", @"Jane", @"John",@"John", nil];
        NSCountedSet *set = [[NSCountedSet alloc] initWithArray:names];
        NSMutableArray *repeatedArray = [[NSMutableArray alloc] init];
        for (id item in set)
        {
            NSLog(@"Name=%@, Count=%lu", item, (unsigned long)[set countForObject:item]);
            if((unsigned long)[set countForObject:item]>1){
                NSLog(@"of repeated element-----=%@",item);
                for(int i=0;i<[set countForObject:item];i++)
                 {
                    [repeatedArray addObject:item];
                 }

        }

输出:约翰,约翰,约翰