谓词不敏感搜索两个字符串数组

时间:2015-11-27 05:01:30

标签: ios objective-c core-data nsmutablearray nspredicate

我试图从两个数组获得常见值,但是不敏感的匹配。但是不能成功。谓词是错误的。

    NSMutableArray *tempArray1 = [NSMutableArray arrayWithObjects:@"apple", @"cat", nil];
    NSMutableArray *tempArray2 = [NSMutableArray arrayWithObjects:@"APPLE", @"CAT", nil];
   // NSPredicate *resultPredicate1 = [NSPredicate predicateWithFormat:@"SELF IN [cd] %@", tempArray1];
    NSPredicate *resultPredicate1 = [NSPredicate predicateWithFormat:@"SELF [cd] IN  %@", tempArray1];
    NSMutableArray *arr_filteredtest = [NSMutableArray arrayWithArray:[tempArray2 filteredArrayUsingPredicate:resultPredicate1]];
    NSLog(@"%lu",(unsigned long)arr_filteredtest.count);

3 个答案:

答案 0 :(得分:0)

如果您需要两个数组中不区分大小写的唯一集,首先必须小写或大写所有字符串,然后创建NSSet

NSMutableArray *joindArr = [NSArray arrayWithArray:tempArray1, nil];
[joindArr addObjectsFromArray:tempArray2];
NSMutableArray *arr1 = [[NSMutableArray alloc]init]; //make a nsmutableArray 
for (int i = 0; i<[arr count]; i++) {
    [arr1 addObject:[[arr objectAtIndex:i]lowercaseString]];
}
NSSet *set = [NSSet setWithArray:(NSArray*)arr1];//this set has unique values

答案 1 :(得分:0)

您可以使用NSSet实现交叉,遗憾的是,使用NSSet的搜索区分大小写。

1.将两个数组转换为普通大小写,upperCaselowerCase

2.使用intersectSet获取结果

示例:

NSMutableArray *tempArray1 = [NSMutableArray arrayWithObjects:@"apple", @"cat", nil];
NSMutableArray *tempArray2 = [NSMutableArray arrayWithObjects:@"APPLE", @"CAT", nil];

tempArray2 = [self convertStringObjectsToLoweCase:tempArray2]; //convert all elements to lower case/ upper case
NSSet *set1 = [NSSet setWithArray:tempArray1];
NSSet *set2 = [NSSet setWithArray:tempArray2];

NSMutableSet *mutableSet = [NSMutableSet setWithSet:set1]; //Initialize with parent array,usually array with more elements
[mutableSet intersectSet:set2];
NSArray *arrayContainingCommonObjects = [mutableSet allObjects];
NSLog(@"arrayContainingCommonObjects : %@",arrayContainingCommonObjects);

使用以下帮助方法

- (NSMutableArray *)convertStringObjectsToLoweCase:(NSMutableArray *)inputArray
{
    [inputArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:[NSString class]]) {
            NSString *loweCaseString = [(NSString *)obj lowercaseString];
            [inputArray replaceObjectAtIndex:idx withObject:loweCaseString];
        }
    }];
    return  inputArray;
}

<强>输出:

  

arrayContainingCommonObjects :(       苹果,       猫)

答案 2 :(得分:-1)

我认为你应该尝试这个

    NSMutableArray *tempArray1 = [NSMutableArray arrayWithObjects:@"apple", @"cat", nil];
    NSMutableArray *tempArray2 = [NSMutableArray arrayWithObjects:@"apple", @"CAT", nil];
    NSMutableSet *intersection = [NSMutableSet setWithArray:tempArray1];
    [intersection intersectSet:[NSSet setWithArray:tempArray2]];
    NSArray *NEW_ARR = [intersection allObjects];
    NSLog(@"new arry::  %@",NEW_ARR);