Case-Insensitive array search

2020-07-30 01:52发布

问题:

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]) {

}

回答1:

Not that hard:

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


回答2:

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;
}


回答3:

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!");
 }