19

NSArrayで特定の文字列を検索したいと思います。

例:

NSArrayには、「dog」、「cat」、「fat dog」、「thing」、「anotherthing」、「heckhere'sanotherthing」というオブジェクトがあります。

「another」という単語を検索して結果を1つの配列に入れ、もう1つの非結果を、さらにフィルタリングできる別の配列に入れたいと思います。

4

3 に答える 3

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];
于 2009-12-06T06:50:38.253 に答える
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];
}
于 2009-12-06T00:18:09.060 に答える
1

ドキュメントごとに「indexOfObjectIdenticalTo:」は、渡したオブジェクトと同じメモリアドレスを持つ最初のオブジェクトのインデックスを返すため、機能しません。

配列をトラバースして比較する必要があります。

于 2012-02-21T05:11:54.517 に答える