2011-05-18 8 views
28

Cuando intento extraer una cadena de una cadena más grande, me da un error de rango o índice fuera de límites. Podría estar pasando por alto algo realmente obvio aquí. Gracias.Extracción de una cadena con substringWithRange: da "índice fuera de límites"

NSString *title = [TBXML textForElement:title1]; 
TBXMLElement * description1 = [TBXML childElementNamed:@"description" parentElement:item1]; 
NSString *description = [TBXML textForElement:description1]; 
NSMutableString *des1 = [NSMutableString stringWithString:description]; 

//search for <pre> tag for its location in the string 
NSRange match; 
NSRange match1; 
match = [des1 rangeOfString: @"<pre>"]; 
match1 = [des1 rangeOfString: @"</pre>"]; 
NSLog(@"%i,%i",match.location,match1.location); 
NSString *newDes = [des1 substringWithRange: NSMakeRange (match.location+5, match1.location-1)]; //<---This is the line causing the error 

NSLog(@"title=%@",title); 
NSLog(@"description=%@",newDes); 

UPDATE: La segunda parte de la gama es una longitud, no el punto final. D'oh!

+2

Usted debe poner su "solución" como respuesta y aceptarlo. – LucasTizma

Respuesta

36

El segundo parámetro pasado a NSMakeRange no es la ubicación final, es la longitud del rango.

Así que el código anterior intenta encontrar una subcadena que comienza en el primer carácter siguiente <pre> y termina N caracteres después de eso, donde N es el índice del último carácter antes dentro de toda la cadena de.

Ejemplo: en la cadena "wholeString<pre>test</pre>noMore" ", la primera 't' de 'prueba' tiene el índice 16 (primer carácter tiene índice 0), y la final 't' de 'prueba' tiene, por lo tanto, el índice 19. El código anterior llamaría al NSMakeRange(16, 19), que incluiría 19 caracteres, comenzando con la primera 't' de 'prueba'. Pero solo hay 15 caracteres, inclusive, desde la primera 't' de 'prueba' hasta el final de la cadena . Por lo tanto, se obtiene el fuera de límites excepción.

lo que necesita es llamar NSRange con la longitud apropiada. para el fin anterior, que sería NSMakeRange(match.location+5, match1.location - (match.location+5))

6

Try este

NSString *string = @"www.google.com/api/123456?google/apple/document1234/"; 
//divide the above string into two parts. 1st string contain 32 characters and remaining in 2nd string 
NSString *string1 = [string substringWithRange:NSMakeRange(0, 32)]; 
NSString *string2 = [string substringWithRange:NSMakeRange(32, [string length]-[string1 length])]; 
NSLog(@"string 1 = %@", string1); 
NSLog(@"string 2 = %@", string2); 

En string2, soy el cálculo del índice del último carácter

Salida:

string 1 = www.google.com/api/123456?google 
string 2 = /apple/document1234/ 
Cuestiones relacionadas