NSStrings的NSArray,数组包含以string开头的对象

时间:2012-04-19 12:58:09

标签: ios search filter nsstring nsarray

我试图找到以特定字符串开头的NSStrings数组中的所有对象,并返回包含所有这些对象的较小数组。例如,您可以拥有包含对象的数组:

'Cat',
'Dog',
'Dolphin',
'Whale'

当搜索的字符串为do时,将返回一个仅包含DogDolphin个对象的新NSArray。

3 个答案:

答案 0 :(得分:6)

NSString* beginsWithRequirement = @"do";
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] %@", beginsWithRequirement];
NSArray* subArray = [originalArray filteredArrayUsingPredicate:predicate];

有关使用谓词的更多信息,请参阅Predicate Programming Guide

答案 1 :(得分:0)

试试这个 -

-(NSArray *)entriesInArray:(NSArray *)wordsArray whichStartWithString:(NSString *)startString {

    startString = [startString lowercaseString]; // get rid of this for case-sensitive (& the lowercaseString bit in the loop too)
    NSMutableArray *resultsArray = [NSMutableArray array];

    for (NSString *thisString in wordsArray) {
        if ([[thisString lowercaseString] hasPrefix:startString]) [resultsArray addObject:thisString];
    }

    return resultsArray;

}

答案 2 :(得分:0)

尝试使用NSPredicate:

 NSArray *arr = [NSArray arrayWithObjects:@"Dog", 
                                          @"Cat", 
                                          @"Dolphin", 
                                          @"Tiger", nil];
 NSString *search = @"do";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@", search];
 NSArray *result = [arr filteredArrayUsingPredicate:predicate];

有关详细信息,请查看Predicate Programming Guide