在NSArray中搜索字符串

Mat*_* S. 19 search nsstring nsarray

我想通过我的NSArray搜索某个字符串.

例:

NSArray有对象:"狗","猫","胖狗","东西","另一件事","这里是另一回事"

我想搜索单词"another"并将结果放入一个数组,并将另一个非结果放入另一个可以进一步过滤的数组中.

dic*_*ciu 47

如果已知数组中的字符串是不同的,则可以使用集合.在大输入上,NSSet比NSArray更快:

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];
Run Code Online (Sandbox Code Playgroud)

  • 有趣的方式来做到这一点! (3认同)

Ken*_*agh 37

未经测试可能会出现语法错误,但您会明白这一点.

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];
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,这是必要的. (5认同)
  • 自己解决:for(NSAtring*item in inputArray){index ++; if([item rangeOfString:@"another"].location!= NSNotFound){[containsAnother addObject:item]; saveIndex = index - 1; } else [doesntContainAnother addObject:item]; } (2认同)