<span style="background-color: rgb(255, 0, 0);"><span style="color:#ffffff;">1.假如有一个数组array1 和一个数组array2 ,怎么找到数组array1和数组array2中相同的元素 :</span></span>
//获取两个数组中相同的元素
NSArray *array1 = @[@"1",@"2",@"3",@"4"];
NSArray *array2 = @[@"1",@"5",@"6",@"3",@"7"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@",array2];
NSArray *result = [array1 filteredArrayUsingPredicate:predicate];
NSLog(@"%@",result);//输出结果为(1,3)
2.假设有一个数组,这个数组中有重复的元素,怎么获取到所有的元素,把相同的元素剔除掉:
//在有重复元素的数组中挑选出数组中所有的元素,重复的自动剔掉
NSMutableArray *array3 = [NSMutableArray arrayWithObjects:@"1",@"2",@"1",@"3",@"3",@"4", nil];
NSArray *orderedResult = [[NSOrderedSet orderedSetWithArray:array3] array];
NSLog(@"orderedResult -- %@",orderedResult);//输出结果是:orderedResult -- (1,2,3,4)
3.判断一个数组中是否包含某个元素(判断数组array2中是否有 8 ):
NSArray *array2 = @[@"1",@"5",@"6",@"3",@"7"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF IN %@",array2];
BOOL hasObj = [predicate evaluateWithObject:@"1"];
if (hasObj) {
NSLog(@"数组array2包含8");
}
else{
NSLog(@"数组array2不包含8");
}
4.检索出数组中以某字符开头的元素:
// 检索出数组array4中以 n 开头的元素
NSMutableArray *array4 = [NSMutableArray arrayWithObjects:@"qin",@"Nick",@"Michle",@"John", nil];
NSPredicate *iPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] 'n'"];
NSArray *beginWithN = [array4 filteredArrayUsingPredicate:iPredicate];
NSLog(@"beginWithN %@",beginWithN);//结果 (Nick)
5.检索出数组中包含某个字符的元素:
// 检索出数组array4中包含 h 的元素
NSMutableArray *array4 = [NSMutableArray arrayWithObjects:@"qin",@"Nick",@"Michle",@"John", nil];
NSPredicate *hPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'h'"];
NSArray *containsH = [array4 filteredArrayUsingPredicate:hPredicate];
NSLog(@"containsH %@",containsH);//结果 (Michle,John)
