Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 474
TommyG Avatar asked Nov 02 '11 22:11

TommyG


People also ask

Can you do a case-sensitive search?

By default, searches are case-insensitive. You can make your search case-sensitive by using the case filter. For example, the following search returns only results that match the term HelloWorld . It excludes results where the case doesn't match, such as helloWorld or helloworld .

How do you do case insensitive string comparison?

Comparing strings in a case insensitive manner means to compare them without taking care of the uppercase and lowercase letters. To perform this operation the most preferred method is to use either toUpperCase() or toLowerCase() function. toUpperCase() function: The str.

How do you do a case insensitive search in less?

You can also type command -I while less is running. It toggles case sensitivity for searches. -i means ignore case in searches that do not contain uppercase while -I ignores case in all searches.


1 Answers

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.

like image 171
Seva Alekseyev Avatar answered Nov 06 '22 20:11

Seva Alekseyev