Reputation: 4155
I am looking for a way to perform a case insensitive string search within another string in Objective-C. I could find ways to search case sensitive strings, and to compare insensitive case, but not searching + case insensitive.
Examples of the search that I would like to perform:
"john" within "i told JOHN to find me a good search algorithm"
"bad IDEA" within "I think its a really baD idea to post this question"
I prefer to stick to only NSStrings.
Upvotes: 9
Views: 14034
Reputation: 216
If you're using ios 8, you can use NSString's localizedCaseInsensitiveContainsString
- (BOOL)localizedCaseInsensitiveContainsString:(NSString *)aString
localizedCaseInsensitiveContainsString: is the case-insensitive variant. Note that it takes the current locale into effect as well. Locale-independent case-insensitive operation, and other needs can be achieved by calling rangeOfString:options:range:locale: directly.
Upvotes: 8
Reputation: 24902
Here is a self-container solution for Swift:
private func containsKeyword(text: NSString, keyword: String) -> Bool
{
return text.rangeOfString(keyword, options:NSStringCompareOptions.CaseInsensitiveSearch).location != NSNotFound
}
Upvotes: 0
Reputation: 61351
NSRange r = [MyString rangeOfString:@"Boo" options:NSCaseInsensitiveSearch];
Feel free to encapsulate that into a method in a category over NSString, if you do it a lot. Like this:
@interface NSString(MyExtensions)
-(NSRange)rangeOfStringNoCase:(NSString*)s;
@end
@implementation NSString(MyExtensions)
-(NSRange)rangeOfStringNoCase:(NSString*)s
{
return [self rangeOfString:s options:NSCaseInsensitiveSearch];
}
@end
Your code might become more readable with this. Then again, less readable for those unfamiliar.
Upvotes: 31
Reputation: 509
mistagged as c#?
heres some advice for objc
NSRange textRange = [[string lowercaseString] rangeOfString:[substring lowercaseString]];
if(textRange.location != NSNotFound)
{
//Does contain the substring
}
which i got from google at this webpage: http://www.developers-life.com/does-a-nsstring-contain-a-substring.html
does that help your scenario?
Upvotes: 9