2012-04-04 68 views
5

所以,基本上我有一個NSArray過濾NSArray字符串元素

我想在獲得一個陣列的初始數組後,不以給定的前綴開始。

它認爲使用filteredArrayUsingPredicate:是最好的方法;但我不知道我如何能做到這一點...

這是到目前爲止我的代碼(在NSArray類別實際上):

- (NSArray*)filteredByPrefix:(NSString *)pref 
{ 
    NSMutableArray* newArray = [[NSMutableArray alloc] initWithObjects: nil]; 

    for (NSString* s in self) 
    { 
     if ([s hasPrefix:pref]) [newArray addObject:s]; 
    } 

    return newArray; 
} 

是它最可可友好的方法?我想要的是儘可能快的東西...

回答

16

下面是使用filteredArrayUsingPredicate:一個更簡單的方法:

NSArray *filteredArray = [anArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF like %@", [pref stringByAppendingString:@"*"]]; 

這通過檢查,它由你的前綴後跟一個通配符的字符串匹配過濾陣列。

如果要檢查不區分大小寫的前綴,請改爲使用like[c]

+0

很好的答案。謝謝! ;-) – 2012-04-04 09:55:55

+1

謝謝,我用這個來比較字中任何地方的字符串:'[NSPredicate predicateWithFormat:@「SELF like [c]%@」,[NSString stringWithFormat:@「*%@ *」,keyword]]' – atulkhatri 2016-06-05 08:56:34

1

您可以使用-indexesOfObjectsPassingTest :.例如:

NSIndexSet* indexes = [anArray indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { 
    return [obj hasPrefix:pref]; 
}]; 
NSArray* newArray = [anArray objectsAtIndexes:indexes]; 
1

您還可以使用indexOfObjectPassingTest:方法NSArray類。 適用於Mac OS X v10.6及更高版本

@implementation NSArray (hasPrefix) 

-(NSMutableArray *)filteredByPrefix:(NSString *)pref 
{ 
    NSMutableArray* newArray = [[NSMutableArray alloc] initWithCapacity:0]; 

    NSUInteger index = [self indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { 
     if ([ obj hasPrefix:pref]) { 
      [newArray addObject:obj]; 
      return YES; 
     } else 
      return NO; 
    }]; 

    return [newArray autorelease]; 

} 

@end