我有两个数组,
NSArray *First=@[@"a", @"b", @"c",@"d", @"e", @"f",@"g", @"h", @"i", @"j", @"k"];
NSArray *Second=@[@"a",@"d", @"e",@"g",@"i"];
现在在
NSMutableArray *Result=[[NSMutableArray alloc]init];
当我使用NSLog结果数组时,我希望输出为
(bcfhjk)
表示结果数组从第一个数组中删除第二个数组中的元素,且条件为no out using removeObjectAtIndex
Method
谢谢提前。
for (id object in First)
if (![Second containsObject:object]) [Result addObject:object];
下面是在不使用removeObjectAtIndex方法的情况下获得所需输出的代码。试试这个:
NSArray *First=@[@"a", @"b", @"c",@"d", @"e", @"f",@"g", @"h", @"i", @"j", @"k"];
NSArray *Second=@[@"a",@"d", @"e",@"g",@"i"];
NSMutableArray *result=[[NSMutableArray alloc]init];
for (NSString *tempChar in First) {
if (![Second containsObject:tempChar]) {
[result addObject:tempChar];
NSLog(@"result arr :%@",result);
}
}
// *** Most Efficient way to achieve with just 3 Lines of code ***
// *** `NSMutableSet` will do the job for you. ***
// *** method `minusSet` performs subtraction operation between two given sets. ***
NSMutableSet *first = [[NSMutableSet alloc] initWithArray:@[@"a", @"b", @"c",@"d", @"e", @"f",@"g", @"h", @"i", @"j", @"k"]];
NSMutableSet *second = [[NSMutableSet alloc] initWithArray:@[@"a",@"d", @"e",@"g",@"i"]];
[first minusSet:second];
NSLog(@"%@",first);
如果没有循环,可以使用NSSet
存档
NSMutableSet *firstSet1 = [NSMutableSet setWithArray: First];
NSSet *secondSet2 = [NSSet setWithArray: Second];
[firstSet1 minusSet: secondSet2];
NSArray * Result = [firstSet1 allObjects];