开发者

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 comb开发者_运维技巧inations of the given string (trip). Any ideas would be greatly appreciated.

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

}


Not that hard:

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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜