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;
}
usage:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With