TommyG TommyG - 1 month ago 16
Objective-C Question

case insensitive string search - iphone

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.

Answer
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.