0

I want to get strings that have specific length in NSArray.

The array has many elements and I don't want to use fast enumeration.

Is there a possible way?

Jun
  • 3,422
  • 3
  • 28
  • 58
  • No matter how you do it you'll get the same function "under the covers" -- iterate through the array and test the individual strings for their length. Using something like filteredArrayWithPredicate might save a few cycles vs doing it in the straight-forward fashion, or might be slower, hard to predict. – Hot Licks Apr 18 '12 at 11:32
  • (Of course you could always keep separately some sort of list of string lengths, and search that. But then there's the overhead of preparing the list.) – Hot Licks Apr 18 '12 at 11:34

3 Answers3

2

No matter what you do you will be using fast enumeration whether you realize it or not. However, have you considered using an NSPredicate object and the filteredArrayWithPredicate method?

borrrden
  • 33,256
  • 8
  • 74
  • 109
2

This works like a charm:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.length == %d", lenght];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
Christian Schnorr
  • 10,768
  • 8
  • 48
  • 83
0
NSArray *yourArray = [[NSArray alloc] initWithObjects:@"Apple, Orange, Grapes, Cherry, nil"];

for(NSString *element in yourArray){

    if(element.length==yourLength){
        [filteredArray addObject:element];
    }
}

NSLog(@"Filtered array now contains the elements with length %d", yourLength);
NSLog(@"Filtered array--%@", filteredArray);
iDev
  • 23,310
  • 7
  • 60
  • 85
RJR
  • 1,072
  • 2
  • 9
  • 21