how to compare 2 NSMutableArray and get different number of value

只愿长相守 提交于 2019-12-12 05:29:41

问题


I want compare 2 NSMutableArray values and check which indexPath is different and store this numbers of index in one array. for example I have these NSMutableArray :

NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", nil];
NSMutableArray *b = [[NSMutableArray alloc]initWithObjects:@"11",@"2",@"5",@"3",@"53",@"6", nil];

and I want to compare these two NSMutableArray index to index (compare value to value) and tell me that which index of array in these NSMutableArrays is different. for example in two NSMutableArray on top this index is different (0,2,3,4) and I want store this values in certain Array.


回答1:


NSMutableArray* differentIndex;
differentIndex = [[NSMutableArray alloc] init];
for(int i = 0 ; i < [a count]; i++) {
    if(i < [b count]){
        if(![b[i] isEqual:a[i]]){
             [differentIndex addObject:[NSNumber numberWithInt:i]];
         }
    } else {
        [differentIndex addObject:[NSNumber numberWithInt:i]];
    }
}

Now your differentIndex contains all the different index in the arrays. :)




回答2:


NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", nil];
NSMutableArray *b = [[NSMutableArray alloc]initWithObjects:@"11",@"2",@"5",@"3",@"53",@"6", nil];
NSMutableArray *new = [[NSMutableArray alloc]init];
for(int i =0;i<[b count]<=[a count]?[b count]:[a count];i++)
{
    NSString *_keyA = [a objectAtIndex:i];
    NSString *_keyB = [b objectAtIndex:i];
    if ([_keyA isEqualToString:_keyB])
       continue;
    [new addObject:[NSString stringWithFormat:@"%d",i]];
}


来源:https://stackoverflow.com/questions/16814774/how-to-compare-2-nsmutablearray-and-get-different-number-of-value

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