How to get strings with specific length from NSArray?
-
01-06-2021 - |
Question
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?
Solution
This works like a charm:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.length == %d", lenght];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
OTHER TIPS
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?
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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow