Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString hasPrefix: function with case sensitivity

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) {
     // ....
}
like image 424
Mani Avatar asked Feb 24 '14 12:02

Mani


4 Answers

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;
}
like image 138
trojanfoe Avatar answered Oct 05 '22 00:10

trojanfoe


You can always use lowercaseString on both strings and thus forcing the same case. So for example

[[string lowercaseString] hasPrefix:[substring lowercaseString]];
like image 39
Volker Avatar answered Oct 05 '22 00:10

Volker


Nasty way to do is to lower case the both string and than use hasPrefix e.g.

[[mainString lowercaseString] hasPrefix:[stringToFind lowercaseString]];
like image 44
Janak Nirmal Avatar answered Oct 05 '22 00:10

Janak Nirmal


you can do this by

if([[string lowercaseString] hasPrefix:[substring lowercaseString]])
{
NSLog(@"found");
}
like image 22
Sumit Mundra Avatar answered Oct 05 '22 02:10

Sumit Mundra