2009-12-05 7 views
19

Me gustaría buscar a través de mi NSArray una determinada cadena.Buscar a través de NSArray para la cadena

Ejemplo:

NSArray tiene los objetos: "perro", "gato", "perro gordo", "cosa", "otra cosa", "diablos aquí hay otra cosa"

quiero busque la palabra "otro" y coloque los resultados en una matriz, y coloque los otros, sin resultados, en otra matriz que pueda filtrarse más.

Respuesta

37

No se ha probado, por lo que podría tener un error de sintaxis, pero ya entenderá.

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

Sí, es necesario. –

+0

Este código funciona muy bien, pero ¿cómo puedo averiguar el índice en la matriz de la cadena encontrada? –

+2

Sovled it myself: para (elemento NSString * en inputArray) {index ++; if ([elemento rangeOfString: @ "another"]. Location! = NSNotFound) { [contieneAnother addObject: item]; saveIndex = índice - 1; } else [doesntContainAnother addObject: item]; } –

47

Si se sabe que las cadenas dentro de la matriz son distintas, puede usar conjuntos. NSSet es más rápido que NSArray en grandes entradas:

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

¡forma interesante de hacerlo! –

1

que no funcionaría porque según el documento "indexOfObjectIdenticalTo:". Devuelve el índice del primer objeto que tiene la misma dirección de memoria que el objeto está de paso en

necesita recorrer su matriz y comparar.

Cuestiones relacionadas