拆分数组并获取索引

时间:2016-04-04 11:50:20

标签: ios objective-c nsmutablearray

我是这样的数组,

[
  1,
  1,
  1,
  0,
  0,
  0,
  1,
  1,
  0,
  1,
  1
]

在上面的数组中,我需要将01数字以及index分开。我编写了将01放在单独数组中的代码,但我希望它们的索引也在Main数组中,代码如下:

for (int i = 0; i < [Array count]; i++) {
       NSString* strV = [Array objectAtIndex:i];
        NSLog(@"ArrayCount:%@",strV);
         if ([strV isEqual:[NSNumber numberWithInt:0]]) {
                [getArray addObject:strV];
                   }
    }

    NSLog(@"getArray:%@",getArray.description);
}

然后,我怎样才能得到0的索引,请你帮忙。谢谢

2 个答案:

答案 0 :(得分:0)

NSMutableArray *arrayContainZero = [NSMutableArray new];
NSMutableArray *arrayWithZeroIndexes = [NSMutableArray new];
for (NSNumber *numberZero in Array)
{
    if(numberZero.integerValue == 0)
    {
            [arrayContainZero addObject:numberZero];
            [arrayWithZeroIndexes      addObject:@([arrayContainZeroindexOfObject:numberZero])];

    }
}

答案 1 :(得分:0)

 NSArray *mainArr=@[@1,@1,@1,@0,@0,@0,@1,@1,@0,@1,@1];
    NSMutableArray *tempArr=[[NSMutableArray alloc] init];
    for(int i=0;i<[mainArr count];i++){
        if([[mainArr objectAtIndex:i] isEqualToNumber:[NSNumber numberWithInt:0]]){
            NSMutableArray *arr=[[NSMutableArray alloc] initWithArray:tempArr];
            [tempArr removeAllObjects];
            NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:0],@"value",[NSNumber numberWithInt:i],@"index",nil];
            [tempArr addObject:dic];
            [tempArr addObjectsFromArray:arr];
        }else if ([[mainArr objectAtIndex:i] isEqualToNumber:[NSNumber numberWithInt:1]]){
            NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1],@"value",[NSNumber numberWithInt:i],@"index",nil];
            [tempArr addObject:dic];
        }
    }

    NSLog(@"%@",tempArr.description);