【问题标题】:NSArray of NSStrings that an array contains object(s) starting with stringNSArray of NSStrings 数组包含以字符串开头的对象
【发布时间】:2012-04-19 12:58:09
【问题描述】:

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

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

当它搜索的字符串是do 时,返回一个新的NSArray,只包含DogDolphin 对象。

【问题讨论】:

    标签: ios search filter nsstring nsarray


    【解决方案1】:
    NSString* beginsWithRequirement = @"do";
    NSPredicate* predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[cd] %@", beginsWithRequirement];
    NSArray* subArray = [originalArray filteredArrayUsingPredicate:predicate];
    

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

    【讨论】:

    • 那太时髦了。我必须添加“SELF BEGINSWITH[cd] %@”,而不仅仅是使用普通的旧 %@。
    【解决方案2】:

    试试这个 -

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

    【讨论】:

      【解决方案3】:

      尝试使用 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-06
        • 2012-07-14
        • 2014-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-20
        • 1970-01-01
        相关资源
        最近更新 更多