获取重复以及iOS中的数组中的原始项目
我有一个数组,如
(约翰,简,约翰)
我想获得重复,以及像数组的原始元素
(John,John)我可以在这里从代码中获得单一的发生
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); } }
“重复元素的名字—–约翰”,但我想要所有重复元素的发生,如“重复元素名称 – 约翰,约翰”。
尝试使用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);
我不确定你的最终目的,你想要的结果看起来毫无意义。 无论如何,为了学习的目的,以下是一个实现;)
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
试试这个代码使用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]; } }
输出:约翰,约翰,约翰