我想通過我的NSArray搜索某個字符串。通過NSArray搜索字符串
例子:
的NSArray具有的對象: 「狗」, 「貓」, 「肥狗」, 「事」, 「還有一件事」, 「這裏到底是另一回事」
我想搜索單詞「another」並將結果放入一個數組中,並將其他非結果放入另一個可進一步過濾的數組中。
我想通過我的NSArray搜索某個字符串。通過NSArray搜索字符串
例子:
的NSArray具有的對象: 「狗」, 「貓」, 「肥狗」, 「事」, 「還有一件事」, 「這裏到底是另一回事」
我想搜索單詞「another」並將結果放入一個數組中,並將其他非結果放入另一個可進一步過濾的數組中。
未經測試,因此可能有語法錯誤,但您會明白。
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];
}
如果已知數組內的字符串是不同的,則可以使用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];
有趣的方式來做到這一點! – 2009-12-06 15:00:55
它不會因爲每個文檔工作「indexOfObjectIdenticalTo:」返回具有相同的內存地址爲您傳遞的對象的第一個對象的索引
你需要遍歷你的數組並進行比較。
是的,這是必要的。 – 2009-12-06 05:05:56
這段代碼工作的很好,但我怎麼能找到找到的字符串數組中的索引? – 2011-06-08 13:54:14
自己撐起來: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