web-dev-qa-db-fra.com

Extraire une chaîne avec substringWithRange: donne "index out of bounds"

Lorsque j'essaie d'extraire une chaîne d'une chaîne plus grande, cela me donne une erreur de plage ou d'index hors limites. Je pourrais oublier quelque chose de vraiment évident ici. Merci.

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);

MISE À JOUR: La 2ème partie de la plage est une longueur, pas le point final. D'oh!

29
Ray Y

Le deuxième paramètre transmis à NSMakeRange n'est pas l'emplacement final, c'est la longueur de la plage.

Ainsi, le code ci-dessus essaie de trouver une sous-chaîne qui commence au premier caractère suivant <pre> Et se termine N caractères après cela, où N est le index du dernier caractère avant dans la chaîne entière.

Exemple: dans la chaîne "wholeString<pre>test</pre>noMore" ", Le premier 't' de 'test' a l'index 16 (le premier caractère a l'index 0), et le 't' final de 'test' a donc l'index 19. Le code ci-dessus appellerait NSMakeRange(16, 19), qui comprendrait 19 caractères, en commençant par le premier "t" de "test". Mais il n'y a que 15 caractères, inclus, à partir du premier "t" de "test" jusqu'à la fin de la chaîne. Par conséquent, vous obtenez l'exception hors limites.

Ce dont vous avez besoin est d'appeler NSRange avec la longueur appropriée. Aux fins ci-dessus, ce serait NSMakeRange(match.location+5, match1.location - (match.location+5))

39
executor21

Essaye ça

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);

Dans string2, je calcule l'index du dernier caractère

Production :

string 1 = www.google.com/api/123456?google
string 2 = /Apple/document1234/
6
vishnu