search if NSString contains value
我有一些由几个字符构成的字符串值,我想检查它们是否存在于另一个nsstring中,不区分大小写和空格。
示例代码:
1 2 3 | NSString *me = @"toBe" ; NSString *target=@"abcdetoBe" ; //than check if me is in target. |
这里我将得到
我已经阅读了如何检查Objective-C中的字符串是否包含另一个字符串?但它是区分大小写的,我需要找到不区分大小写的。
使用一个
1 2 3 4 5 6 7 | NSString *me = @"toBe" ; NSString *target = @"abcdetobe" ; NSRange range = [target rangeOfString: me options: NSCaseInsensitiveSearch]; NSLog(@"found: %@", (range.location != NSNotFound) ? @"Yes" : @"No"); if (range.location != NSNotFound) { // your code } |
nslog输出:
found: Yes
注:1,目标是大小写不敏感的搜索工程案例来证明。
可以在"选项"或"ED"包括:在与
- nscaseinsensitivesearch
- nsliteralsearch
- nsbackwardssearch
- nsanchoredsearch
- nsnumericsearch
- nsdiacriticinsensitivesearch
- nswidthinsensitivesearch
- nsforcedorderingsearch
- nsregularexpressionsearch
1 2 3 4 5 6 7 | -(BOOL)substring:(NSString *)substr existsInString:(NSString *)str { if(!([str rangeOfString:substr options:NSCaseInsensitiveSearch].length==0)) { return YES; } return NO; } |
用法:
1 2 3 4 5 6 7 8 | NSString *me = @"toBe"; NSString *target=@"abcdetoBe"; if([self substring:me existsInString:target]) { NSLog(@"It exists!"); } else { NSLog(@"It does not exist!"); } |
作为一个ios8的发布,苹果增加了一个新
斯威夫特:
1 2 3 4 | let string: NSString ="ToSearchFor" let substring: NSString ="earch" string.localizedCaseInsensitiveContainsString(substring) // true |
Objective-C。
1 2 3 4 | NSString *string = @"ToSearchFor"; NSString *substring = @"earch"; [string localizedCaseInsensitiveContainsString:substring]; //true |