search if NSString contains value
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 .
Example code :
NSString *me = @"toBe" ;
NSString *target=@"abcdetoBe" ;
//than check if me is in target.
Here i will get true
because me
exist in target
. How can i check for such condition ?
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..
Use the option NSCaseInsensitiveSearch
with 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:
found: Yes
Note: I changed the target to demonstrate that case insensitive search works.
The options can be "or'ed" together and include:
-(BOOL)substring:(NSString *)substr existsInString:(NSString *)str {
if(!([str rangeOfString:substr options:NSCaseInsensitiveSearch].length==0)) {
return YES;
}
return NO;
}
用法:
NSString *me = @"toBe";
NSString *target=@"abcdetoBe";
if([self substring:me existsInString:target]) {
NSLog(@"It exists!");
}
else {
NSLog(@"It does not exist!");
}
As with the release of iOS8, Apple added a new method to NSString
called localizedCaseInsensitiveContainsString
. This will exactly do what you want:
Swift:
let string: NSString = "ToSearchFor"
let substring: NSString = "earch"
string.localizedCaseInsensitiveContainsString(substring) // true
Objective-C:
NSString *string = @"ToSearchFor";
NSString *substring = @"earch";
[string localizedCaseInsensitiveContainsString:substring]; //true
链接地址: http://www.djcxy.com/p/73996.html
上一篇: C字符串功能:包含字符串
下一篇: 搜索NSString是否包含值