NSString hasPrefix: function with case sensitivity
From Apple themselves:
NSString *searchString = @"age";
NSString *beginsTest = @"Agencies";
NSRange prefixRange = [beginsTest rangeOfString:searchString
options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
// prefixRange = {0, 3}
NSString *endsTest = @"BRICOLAGE";
NSRange suffixRange = [endsTest rangeOfString:searchString
options:(NSAnchoredSearch | NSCaseInsensitiveSearch | NSBackwardsSearch)];
// suffixRange = {6, 3}
This could be wrapped into an easy-to-use method:
- (BOOL) string:(NSString *)string
hasPrefix:(NSString *)prefix
caseInsensitive:(BOOL)caseInsensitive {
if (!caseInsensitive)
return [string hasPrefix:prefix];
const NSStringCompareOptions options = NSAnchoredSearch|NSCaseInsensitiveSearch;
NSRange prefixRange = [string rangeOfString:prefix
options:options];
return prefixRange.location == 0 && prefixRange.length > 0;
}
You can always use lowercaseString
on both strings and thus forcing the same case. So for example
[[string lowercaseString] hasPrefix:[substring lowercaseString]];
Nasty way to do is to lower case the both string and than use hasPrefix e.g.
[[mainString lowercaseString] hasPrefix:[stringToFind lowercaseString]];