- (void)viewDidLoad {
[super viewDidLoad];
//统计数组相同元素的个数
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
//需要统计的数组
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"2",@"3",@"3",@"3", nil];
NSSet *set = [NSSet setWithArray:array];
for (NSString *setstring in set) {
//需要去掉的元素数组
NSMutableArray *filteredArray = [[NSMutableArray alloc]initWithObjects:setstring, nil];
NSMutableArray *dataArray = array;
NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",filteredArray];
//过滤数组
NSArray * reslutFilteredArray = [dataArray filteredArrayUsingPredicate:filterPredicate];
NSLog(@"Reslut Filtered Array = %@",reslutFilteredArray);
int number = (int)(dataArray.count-reslutFilteredArray.count);
NSLog(@"number :%d",number);
[dic setObject:[NSString stringWithFormat:@"%d",number] forKey:setstring];
}
NSLog(@"dic :%@",dic);
//---------------------------------------------------------------------------------------
//参考数组筛选:
//需要去掉的元素数组
NSMutableArray *filteredArray = [[NSMutableArray alloc]initWithObjects:@"1",@"4", nil];
//需要被筛选的数组
NSMutableArray *dataArray = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"1",@"4",@"6",@"1",@"1",@"4",@"1",@"6",@"4", nil];
/*
方法一:利用NSPredicate
注:NSPredicate所属Cocoa框架,在密码、用户名等正则判断中经常用到。
类似于SQL语句
NOT 不是
SELF 代表字符串本身
IN 范围运算符
那么NOT (SELF IN %@) 意思就是:不是这里所指定的字符串的值
*/
NSPredicate * filterPredicate = [NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",filteredArray];
//过滤数组
NSArray * reslutFilteredArray = [dataArray filteredArrayUsingPredicate:filterPredicate];
NSLog(@"Reslut Filtered Array = %@",reslutFilteredArray);
/*
结果:
Reslut Filtered Array = (
2,
6,
6
)
*/
/*
方法二:从后往前遍历数组,然后匹配删除
*/
int i = (int)[dataArray count]-1;
for(;i >= 0;i --){
//containsObject 判断元素是否存在于数组中(根据两者的内存地址判断,相同:YES 不同:NO)
if([filteredArray containsObject:[dataArray objectAtIndex:i]]) {
[dataArray removeObjectAtIndex:i];
}
}
NSLog(@"Data Array = %@",dataArray);
/*
结果:
Data Array = (
2,
6,
6
)
*/
}