處理字串真的是一門大學問,這次我想要搜尋某個關鍵字,是英文且不區分大小寫,此時我可以怎麼做?
我們可以使用Predicate設定Case-Insensitive,翻譯成中文是謂詞不區分大小寫,真是彆扭啊~
Apple官方文件有段描述:
String comparisons are by default case and diacritic sensitive. You can modify an operator using the key characters c and d within square braces to specify case and diacritic insensitivity respectively, for example firstName BEGINSWITH[cd] $FIRST_NAME.
意思就是只要在Predicate中加入[cd],就能找到英文不區分大小寫的字串囉~
我這裡展示的是可以輸入多個關鍵字,然後同時把多個關鍵字丟到我們想找尋的字串堆中。比如「happy」「man」這兩個關鍵字。
/** Theme: Predicate for Case-Insensitive IDE: Xcode 6 Language: Objective C Date: 104/05/12 Author: HappyMan Blog: https://cg2010studio.wordpress.com/ */ // 使用predicate來搜尋AND包含name,text,tag NSArray *searchArray = [matchText componentsSeparatedByString:@" "]; NSMutableArray *parr = [NSMutableArray array]; for (int i = 0; i < [searchArray count]; i++) { [parr addObject:[NSPredicate predicateWithFormat:@"(SELF CONTAINS[cd] %@)", searchArray[i]]]; } NSPredicate *thePredicate = [NSCompoundPredicate andPredicateWithSubpredicates:parr]; // 組合text,name,tag NSString *compoundStr = [NSString stringWithFormat:@"%@ %@ %@", originalString, senderName, tagName]; BOOL isMatch = [thePredicate evaluateWithObject:compoundStr];
我預先準備四個字串:
- HappyMan~
- Happy man:)
- happyMan
- happyman
接著以happy man兩個關鍵字去搜尋⋯⋯
通通都找到了呢:)~
註:
andPredicateWithSubpredicates
「and」表示所有predicate都要符合。而「or」,則表示其中一個predicate符合即可。
參考:NSPredicate case-insensitive matching on to-many relationship、Predicate Format String Syntax。
隨意留個言吧:)~