2013-09-24 54 views
0

我有兩個MutableArray類似。如何比較兩個MutableArrays並在iphone中顯示不匹配的值?

NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@"Apple", @"Orange", @"Grapes", @"Banana", nil]; 

NSMutableArray *array1=[[NSMutableArray alloc]initWithObjects:@"Apple", @"Orange", @"Grapes", nil]; 

現在我要比較兩個易變陣列並顯示無與倫比的對象「香蕉」成一個字符串。

我很清新iOS,所以任何人都會向我發送該問題的代碼。

在此先感謝。

回答

2

正如其他人建議,NSSet中可能是你最好的選擇。然而,由於*數組是可變的,你可以簡單地從其中包含的對象中刪除* array1

NSMutableArray *array=[[NSMutableArray alloc]initWithObjects:@"Apple", @"Orange", @"Grapes", @"Banana", nil]; 
NSMutableArray *array1=[[NSMutableArray alloc]initWithObjects:@"Apple", @"Orange", @"Grapes", nil]; 

[array removeObjectsInArray:array1]; 
NSLog(@"array: %@", array);   // array: (Banana) 

// if you require result as a string 
NSString *objectsAsString = [array componentsJoinedByString:@", "]; 
NSLog(@"objects as string: %@", objectsAsString); // objects as string: Banana 
0
for(int i=0;i<[array count];i++) 
    { 

    NSString *str1 = [array objectAtIndex:i]; 
    for(int j=0;j<[array1 count];j++) 
    { 

    NSString *str2 = [array1 objectAtIndex:j]; 
    if([str1 isEqualToString:str2]) 
    { 
    //do something which you want i.e add the values to some other array 
    } 
    } 

} 
+0

運行代碼並找到Apple,Orange的答案。 – Subrat

+0

我已經運行它,發現蘋果,桔子和葡萄匹配 – Tendulkar

+0

是的我的錯誤。是與你的輸出匹配。 – Subrat

0

你應該使用NSSet用於此目的

NSSet *set1 = [NSSet setWithObjects:@"a", @"s", @"d", @"f", nil]; 
NSSet *set2 = [NSSet setWithObjects:@"a", @"s", nil]; 

NSMutableSet *notInSet1 = [NSMutableSet setWithSet:set2]; 
[notInSet1 minusSet:set1]; 
NSMutableSet *notInSet2 = [NSMutableSet setWithSet:set1]; 
[notInSet2 minusSet:set2]; 

NSMutableSet *symmetricDifference = [NSMutableSet setWithSet:notInSet1]; 
[symmetricDifference unionSet:notInSet2]; 
0
NSArray *array1 = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",nil]; 
NSArray *array2 = [[NSArray alloc] initWithObjects:@"a",@"d",@"c",nil]; 
NSMutableArray *ary_result = [[NSMutableArray alloc] init]; 
NSMutableArray *ary_resultUnmatched = [[NSMutableArray alloc] init]; 
for(int i = 0;i<[array1 count];i++) 
{ 
    for(int j= 0;j<[array2 count];j++) 
    { 
     if([[array1 objectAtIndex:i] isEqualToString:[array2 objectAtIndex:j]]) 
     { 
      [ary_result addObject:[array1 objectAtIndex:i]]; 
     } else { 
      [ary_resultUnmatched addObject:[array1 objectAtIndex:i]]; 
     } 
    } 
} 
NSLog(@"%@",ary_result);//it will print a,c 
NSLog(@"%@",ary_resultUnmatched);//it will print b,d 

所以在其他條件你有你的未匹配的值

相關問題