2009-12-05 69 views
19

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

例子:

的NSArray具有的对象: “狗”, “猫”, “肥狗”, “事”, “还有一件事”, “这里到底是另一回事”

我想搜索单词“another”并将结果放入一个数组中,并将其他非结果放入另一个可进一步过滤的数组中。

回答

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

是的,这是必要的。 – 2009-12-06 05:05:56

+0

这段代码工作的很好,但我怎么能找到找到的字符串数组中的索引? – 2011-06-08 13:54:14

+2

自己撑起来:for(NSString * item in inputArray) {index ++; ([item rangeOfString:@“another”]。location!= NSNotFound){包含另一个addObject:item]; saveIndex = index - 1; } else [doesntContainAnother addObject:item]; } – 2011-06-08 14:11:29

47

如果已知数组内的字符串是不同的,则可以使用sets。的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]; 
+3

有趣的方式来做到这一点! – 2009-12-06 15:00:55

1

它不会因为每个文档工作“indexOfObjectIdenticalTo:”返回具有相同的内存地址为您传递的对象的第一个对象的索引

你需要遍历你的数组并进行比较。