anshul
anshul

Reputation: 846

searching something like %ab% in NSArray

I want to search my NSArray object for some strings which contain a particular sequence of letters at any position. It should be similar to something like the "LIKE operator" we use in database. For example, I want to search for all the string containing 'ab' in my NSArray object.

Upvotes: 0

Views: 537

Answers (2)

tim
tim

Reputation: 1682

You can filter an Array using a predicate:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"abs", @"bar", @"foo", @"fabs", nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] 'ab'"];
NSArray *filteredArray = [array filteredArrayUsingPredicate:predicate];

Upvotes: 2

Rog
Rog

Reputation: 18670

Assuming you have an array of NSString objects...

NSArray *array = [NSArray arrayWithObjects:@"String one", @"String two", @"String three", nil];
for (NSString *string in array)
{
    if ([string rangeOfString:@"XYZ"].location != NSNotFound)
        NSLog (@"Found one: %@", string);            
}

[edit]

To add that you can also use the rangeOfString:options: method if you need to case insensitive searches amongst others.

Upvotes: 1

Related Questions