开发者

How to split array of strings based on string's length?

I hope it can be done with "NSPredicate". I have array of strings in thousands and i want to split into array using string length. i.e. Strings with length 2 will come into an array. Strings with length 3 will come in an array so on. Is it possible using "NSPredicate". I checked NSPredicate Cl开发者_如何学Pythonass Reference. But could not find useful example.

Thanks

Neal


I hope following code solve your problem.

 NSString *regExp = @"[A-Z0-9a-z]{2,3}";
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regExp];

    NSMutableArray *array=[NSMutableArray new];
    [array addObject:@"ABC"];
    [array addObject:@"AGADF"];
    [array addObject:@"ADFADS"];
    [array addObject:@"DD"];
    [array addObject:@"DFA"];

    NSArray *filtered = [array filteredArrayUsingPredicate:predicate];

    NSLog(@"filter : %@",filtered);


I believe the NSPredicate with regex might not be efficient. This code should solve it for sure and more efficiently, you'll get the dictionary where keys are the string lengths, and objects are the corresponding arrays containing strings of certain length.

NSMutableDictionary* filtered = [NSMutableDictionary dictionary];
NSMutableArray* strings =[NSMutableArray array];
[strings addObject:@"ABC"];
[strings addObject:@"AGADF"];
[strings addObject:@"ADFADS"];
[strings addObject:@"DD"];
[strings addObject:@"DFA"];


for (NSString* s in strings) {
    NSNumber* key = [NSNumber numberWithInt:[s length]];
    NSMutableArray* arr = [filtered objectForKey:key];
    if (nil==arr) {
        arr = [NSMutableArray array];
        [filtered setObject:arr forKey:key];
    } 
    [arr addObject:s];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜