2009-12-05 6 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

예, 필요합니다. –

+0

이 코드는 훌륭하게 작동하지만 발견 된 문자열의 배열에서 인덱스를 어떻게 찾을 수 있습니까? –

+2

Sovled it myself : for (inputString의 NSString * 항목) {index ++; if ([item rangeOfString : @ "another"]. 위치! = NSNotFound) { [containsAnother addObject : item]; saveIndex = 인덱스 - 1; } else [addntContainAnother addObject : item]; } –

47

배열 내의 문자열이 구분되는 것으로 알려진 경우 세트를 사용할 수 있습니다.

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

재미있는 방법! –

1

이 때문에 문서에 따라 작동하지 않을 것 "indexOfObjectIdenticalTo :"NSSet 큰 입력에있는 NSArray 다음 빠릅니다. 당신이 전달하는 객체와 같은 메모리 주소가 첫 번째 개체의 인덱스를 반환

배열을 탐색하여 비교해야합니다.

관련 문제