views:

2201

answers:

2

I would like to search through my NSArray for a certain string.

Example:

NSArray has objects: "dog", "cat", "fat dog", "thing", "another thing", "heck here's another thing"

I want to search for the word "another" and put the results into one array, and have the other, non results, into another array that can be filtered further.

+5  A: 

Bored so here's some code. Not tested so might have a syntax error, but you'll get the idea.

NSArray* inputArray = [NSArray arrayWithObjects:@"dog", @"cat", @"fat dog", @"thing", @"another thing", @"heck here's another thing", nil];

NSMutableArray* containsAnother = [NSMutableArray array];
NSMutableArray* doesntContainAnother = [NSMutableArray array];

for (NSString* item in inputArray)
{
  if ([item rangeOfString:@"another"].location != NSNotFound)
    [containsAnother addObject:item];
  else
    [doesntContainAnother addObject:item];
}
Ken Aspeslagh
The only error I see is the = [NSMutableArray array] doesn't look necessary. I'll try it out when I get to the computer that has the source code on it.
Matt S.
Yes, it is necessary.
Ken Aspeslagh
+3  A: 

If the strings inside the array are known to be distinct, you can use sets. NSSet is faster then NSArray on large inputs:

NSArray * inputArray = [NSMutableArray arrayWithObjects:@"one", @"two", @"one again", nil];

NSMutableSet * matches = [NSMutableSet setWithArray:inputArray];
[matches filterUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[c] 'one'"]];

NSMutableSet * notmatches = [NSMutableSet setWithArray:inputArray];
[notmatches  minusSet:matches];
diciu
interesting way to do it!
Ken Aspeslagh