Search through NSArray for string

这一生的挚爱 提交于 2019-11-27 10:23:23

问题


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

Example:

NSArray has the 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.


回答1:


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];
}



回答2:


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];



回答3:


It would not work because as per document "indexOfObjectIdenticalTo:" returns the index of the first object that has the same memory address as the object you are passing in.

you need to traverse through your array and compare.



来源:https://stackoverflow.com/questions/1853801/search-through-nsarray-for-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!