iOS统计数组相同元素的个数

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //统计数组相同元素的个数
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    //需要统计的数组
    NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"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);
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //参考数组筛选:
    
    //需要去掉的元素数组
    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
     )
     */
    
}


转载请注明出处http://blog.csdn.net/chen_gp_x

©️2020 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值