NSPredicate that ignores whitespaces

允我心安 提交于 2019-12-03 14:00:36

How about defining something like this:

+ (NSPredicate *)myPredicateWithKey:(NSString *)userInputKey {
    return [NSPredicate predicateWithBlock:^BOOL(NSString *evaluatedString, NSDictionary *bindings) {
        // remove all whitespace from both strings
        NSString *strippedString=[[evaluatedString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
        NSString *strippedKey=[[userInputKey componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
        return [strippedString caseInsensitiveCompare:strippedKey]==NSOrderedSame;
    }];
}

Then use it like this:

NSArray *testArray=[NSArray arrayWithObjects:@"abc", @"a bc", @"A B C", @"AB", @"a B d", @"A     bC", nil];
NSArray *filteredArray=[testArray filteredArrayUsingPredicate:[MyClass myPredicateWithKey:@"a B C"]];               
NSLog(@"filteredArray: %@", filteredArray);

The result is:

2012-04-10 13:32:11.978 Untitled 2[49613:707] filteredArray: (
    abc,
    "a bc",
    "A B C",
    "A     bC"
)
Vahid

Swift 4:

func ignoreWhiteSpacesPredicate(id: String) -> NSPredicate {
    return NSPredicate(block: { (evel, binding) -> Bool in
        guard let str = evel as? String else {return false}
        let strippedString = str.components(separatedBy: CharacterSet.whitespaces).joined(separator: "")
        let strippedKey = id.components(separatedBy: CharacterSet.whitespaces).joined(separator: "")
        return strippedString.caseInsensitiveCompare(strippedKey) == ComparisonResult.orderedSame
    })
}

Example:

let testArray:NSArray =  ["abc", "a bc", "A B C", "AB", "a B d", "A     bC"]
let filteredArray = testArray.filtered(using: ignoreWhiteSpacesPredicate(id: "a B C")) 

Result:

["abc", "a bc", "A B C", "A bC"]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!