Check if String contains any String from array

后端 未结 3 720
别那么骄傲
别那么骄傲 2021-01-21 01:47

I know I can check if a string contains another string like this

NSString *string = @\"hello bla bla\";
if ([string rangeOfString:@\"bla\"].location == NSNotFoun         


        
3条回答
  •  北海茫月
    2021-01-21 01:54

    There you go:

    NSArray* arrRet = [myArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id  __nonnull evaluatedObject, NSDictionary * __nullable bindings) {
        for(NSString* val in valuesArray) {
            if ([evaluatedObject rangeOfString:val].location != NSNotFound)
                return true;
        }
        return false;
    }]];
    

    arrRet contains exactly the two desired strings.

    A little bit more magic later you have your code without writing a loop :P

    NSArray* arrRet = [myArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id  evaluatedObject, NSDictionary * bindings) {
        BOOL __block match = false;
        [valuesArray enumerateObjectsUsingBlock:^(id  __nonnull obj, NSUInteger idx, BOOL * __nonnull stop) {
            *stop = match = [evaluatedObject rangeOfString:obj].location != NSNotFound;
        }];
        return match;
    }]];
    

提交回复
热议问题