Simple and may asked many time but little trick with this. We know, NSString doesn't work with case sensitivity for hasPrefix: method.
NSString *string = @"Xyzabcdedfghij";
NSString *substring = @"xyz";
if ([string hasPrefix:substring])
NSLog(@"string has prefix "); // won't get here.
Question is:
Is there any built-in method for resolve this issue? I mean, hasPrefix:
with case sensitive?
I could use below answer at least case. But want to know if there is any method which better than this..?
Known answer:(lease case)
if ([[test substringWithRange:NSMakeRange(0,3)] caseInsensitiveCompare:@"xyz"] == NSOrderedSame) {
// ....
}
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]];
you can do this by
if([[string lowercaseString] hasPrefix:[substring lowercaseString]])
{
NSLog(@"found");
}
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