比较两个数组并设置if else

时间:2013-08-10 10:57:41

标签: ios arrays compare

我需要比较两个数组(A& B),而不是属于B的A元素我需要设置一个if语句。只是为了更好地解释一下:

if (elementOfArrayA belong AlsoToarrayB) {
        //do something
    }else{
        //do something else
    }

有人可以帮助我吗? 感谢

5 个答案:

答案 0 :(得分:2)

NSArray有一个名为containsObject:的实例方法。

如需进一步说明,请检查this

答案 1 :(得分:2)

使用以下代码比较两个数组:

    NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",nil];
    NSArray *array2 = [[NSArray alloc] initWithObjects:@"a",@"d",@"c",nil];

     for(int i = 0;i<[array1 count];i++)
        {
            for(int j= 0;j<[array2 count];j++)
            {
                if([[array1 objectAtIndex:i] isEqualToString:[array2 objectAtIndex:j]])
                {

                }  else {

                }
            }
        }

答案 2 :(得分:2)

比较两个数组:

if([arrayA isEqualToArray:arrayB]){
//the two arrays A and B are equals
}

上面的代码将测试两个数组的所有元素,以检查它们是否满足isEqual测试,因此不需要for循环数组。

如果要检查arrayB中是否包含arrayA的元素,请使用以下方法:

id firstCommonObject = [arrayA firstObjectCommonWithArray:arrayB];

if(firstCommonObject != nil){
  //a common object between arrayA and arrayB has been found

}else{
  //no common objects between both arrays
}

答案 3 :(得分:1)

// Method 1 - Simplest method to solve above problem (Use NSArray's containsObject method)
NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",@"e", nil];
NSArray *array2 = [[NSArray alloc] initWithObjects:@"a",@"d",@"c",@"f", nil];

for(id i in array1){
    if ([array2 containsObject:i]) {
        // do something
    }
    else {
        // do something else
    }
}

// Method 2 - Another method (Use NSString's isEqualToString method)
NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",@"e", nil];
NSArray *array2 = [[NSArray alloc] initWithObjects:@"a",@"d",@"c",@"f", nil];

for(id i in array1){
    for(id j in array2){
        if ([i isEqualToString:j]) {
            // do something
        }
        else {
            //do something else
        }
    }
}

答案 4 :(得分:0)

它可能对你有帮助......

-(void)methodFour
{
    NSArray *arr1 = [[NSArray alloc]initWithObjects:@"a2223a",@"ab33b",@"a1acdf",@"ac23c45", nil];
    NSArray *arr11 =  [arr1 sortedArrayUsingSelector:@selector(localizedCompare:)];
    NSLog(@"%@",arr11);

    NSArray *arr2 = [[NSArray alloc]initWithObjects:@"ab33b",@"ac23c45",@"a1acdf",@"a2223a", nil];
    NSArray *arr22= [arr2 sortedArrayUsingSelector:@selector(localizedCompare:)];
    [self firstArray:arr11 secondArray:arr22];
   }
-(void)firstArray:(NSArray *)array1 secondArray:(NSArray *)array2
{
    if ([array1 isEqualToArray:array2])
    {
        NSLog(@"equal");

    }
    else
    {
        NSLog(@"Not equal");

    }
}