开发者

Case-Insensitive array search

开发者 https://www.devze.com 2023-02-24 21:43 出处:网络
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 str

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

精彩评论

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

关注公众号