objective-c 搜索 NSString 是否包含值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21969147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
search if NSString contains value
提问by Curnelious
I have some string value which constructed from a few characters , and i want to check if they exist in another NSString, without case sensitive, and spaces .
我有一些由几个字符构成的字符串值,我想检查它们是否存在于另一个 NSString 中,不区分大小写和空格。
Example code :
示例代码:
NSString *me = @"toBe" ;
NSString *target=@"abcdetoBe" ;
//than check if me is in target.
Here i will get truebecause meexist in target.
How can i check for such condition ?
在这里我会得到,true因为me存在于target. 我如何检查这种情况?
I have read How do I check if a string contains another string in Objective-C?but its case sensitive and i need to find with no case sensitive..
我已阅读在 Objective-C 中如何检查字符串是否包含另一个字符串?但它区分大小写,我需要找到不区分大小写的..
回答by zaph
Use the option NSCaseInsensitiveSearchwith rangeOfString:options:
使用选项NSCaseInsensitiveSearch与rangeOfString:options:
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 output:
NSLog 输出:
found: Yes
发现:是
Note: I changed the target to demonstrate that case insensitive search works.
注意:我更改了目标以证明不区分大小写的搜索有效。
The options can be "or'ed" together and include:
选项可以“或”在一起,包括:
- NSCaseInsensitiveSearch
- NSLiteralSearch
- NSBackwardsSearch
- NSAnchoredSearch
- NSNumericSearch
- NSDiacriticInsensitiveSearch
- NSWidthInsensitiveSearch
- NSForcedOrderingSearch
- NSRegularExpressionSearch
- NSCaseInsensitiveSearch
- NSLiteralSearch
- NSBackwardsSearch
- 锚定搜索
- NSNumericSearch
- NSDiacriticInsensitiveSearch
- NSWidthInsensitiveSearch
- NSForcedOrderingSearch
- NSRegularExpressionSearch
回答by Jonathan Gurebo
-(BOOL)substring:(NSString *)substr existsInString:(NSString *)str {
if(!([str rangeOfString:substr options:NSCaseInsensitiveSearch].length==0)) {
return YES;
}
return NO;
}
usage:
用法:
NSString *me = @"toBe";
NSString *target=@"abcdetoBe";
if([self substring:me existsInString:target]) {
NSLog(@"It exists!");
}
else {
NSLog(@"It does not exist!");
}
回答by Alexander
As with the release of iOS8, Apple added a new method to NSStringcalled localizedCaseInsensitiveContainsString. This will exactly do what you want:
随着 iOS8 的发布,Apple 添加了一个新方法来NSString调用localizedCaseInsensitiveContainsString. 这将完全满足您的要求:
Swift:
迅速:
let string: NSString = "ToSearchFor"
let substring: NSString = "earch"
string.localizedCaseInsensitiveContainsString(substring) // true
Objective-C:
目标-C:
NSString *string = @"ToSearchFor";
NSString *substring = @"earch";
[string localizedCaseInsensitiveContainsString:substring]; //true

