2015-02-24 69 views
0

很难解释为什么我需要在数组中重复索引元素。当我试图获取传统方式元素的索引,仅显示一个指数,但我需要获取对前重复的所有索引值 :在NSArray中查找所有重复元素的索引

NSArray *[email protected][@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"]; 
int index = [array indexOfObject:element]; 
NSLog(@"index %d",index); 

在这里,如果我尝试获取的“one指数“这表明指数,但我需要得到的one

+0

你想要所有的索引作为匹配索引或单个索引的数组。 – Nagarajan 2015-02-24 06:35:39

回答

2

进一步索引可以取重复的指标是这样的:

NSArray *[email protected][@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"]; 
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) 
{ 
    if ([obj isEqualToString:@"one"]) 
    { 
     NSLog(@"index %d",idx); 

    } 
}]; 
+0

如果数组已经排序,肯定会有效☺️ – runmad 2015-11-30 14:35:31

+0

它不会对这个数组进行排序 – 2015-12-24 08:19:27

1
int i,count=0; 
for (i = 0; i < [array count]; i++) { 
    if element == [array objectAtIndex:i] { 
     indices[count++] = i; 
    } 
} 

声明一个空数组索引,索引将包含给定元素的所有索引。

2
NSString *element = @"one"; 
NSArray *[email protected][@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"]; 

NSIndexSet *matchingIndexes = [array indexesOfObjectsPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) { 
    return [obj isEqual:element]; 
}]; 

[matchingIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) { 
    NSLog(@"%ld", (long)idx); 
}]; 
1

最终我不认为NSArray方法会帮助你在这里,所以你将不得不写一些非常基本的代码。可能有一个更清晰的答案,但这是一个相当简单的解决方案。

这只是通过数组,并为每个唯一编号创建一个NSDictionary。它假定数组按照您的示例进行排序,因此只需将先前索引的值与当前索引进行比较,以查看它们是否已更改。当它们改变时,它知道它是用这个值完成的,并将字典保存到一个数组中。

NSArray *[email protected][@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"]; 
NSString *priorString = array[0]; 
NSMutableDictionary *duplicatesByKey = [[NSMutableDictionary alloc] init]; 
NSMutableArray *indexesOfDuplicates = [[NSMutableArray alloc] init]; 

int index = 0; 
for (NSString *string in array) { 
    if ([priorString isEqualToString:string]) { 
     [indexesOfDuplicates addObject:[NSNumber numberWithInt:index]]; 
    } else { 
     [duplicatesByKey setObject:indexesOfDuplicates forKey:priorString]; 
     indexesOfDuplicates = [[NSMutableArray alloc] init]; 
     [indexesOfDuplicates addObject:[NSNumber numberWithInt:index]]; 
    } 
    priorString = string; 
    index ++; 
} 
[duplicatesByKey setObject:indexesOfDuplicates forKey:priorString]; 

我希望有帮助。