Greg Richards
Greg Richards

Reputation: 49

Case-Insensitive array search

I am trying to search an NSMutableArray for a string. I am using containsObject: currently but it looks like this is case sensitive. I need to search for all combinations of the given string (trip). Any ideas would be greatly appreciated.

if ([self.theArray containsObject:trip]) {

}

Upvotes: 1

Views: 2333

Answers (3)

pmobley
pmobley

Reputation: 113

Create a category for NSArray and add this function in there.

- (BOOL)containsStringCaseInsensitive:(NSString *)key {
    key = [key lowercaseString];
    for (int i = ([self count] - 1); i >= 0; i--) {
        NSObject * obj = [self objectAtIndex:i];
        if ([obj isKindOfClass:[NSString class]]) {
            NSString * strInArray = [(NSString *)obj lowercaseString];
            if ([key isEqualToString:strInArray]) {
                return YES;
            }
        }
    }

    return NO;
}

Upvotes: 3

NWCoder
NWCoder

Reputation: 5266

How about a block:

__block trip = @"blah";
if (NSNotFound!=[self.theArray indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop)
         {
             if (NSOrderedSame==[(NSString *)obj caseInsensitiveCompare:trip])
             {
                    stop=YES;
                    return YES;
             }
             return NO;
          }])
 {
       NSLog(@"It's a MATCH!");
 }

Upvotes: 0

Jan Gressmann
Jan Gressmann

Reputation: 5541

Not that hard:

BOOL found = NO;
for (NSString* str in self.theArray) {
   if ([str caseInsensitiveCompare:trip] == NSOrderedSame) {
       found = YES;
       break;
   }
}

Upvotes: 11

Related Questions