0

我有一个数组,如

(约翰,简,约翰)

我想获得重复项,以及数组的原始元素,例如

(约翰,约翰)我可以从这里的代码中获得单次出现

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);
    }
} 

“重复元素的名称-----约翰”,但我想要所有重复元素的出现,如“重复元素的名称-----约翰,约翰”。

4

3 回答 3

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);
于 2017-05-05T07:13:04.710 回答
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

于 2017-05-05T06:58:50.210 回答
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];
                 }

        }

输出:约翰,约翰,约翰

于 2017-05-05T08:20:58.470 回答