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