Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a string with substringWithRange: gives "index out of bounds"

When I try to extract a string from a larger string it gives me a range or index out of bounds error. I might be overlooking something really obvious here. Thanks.

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: The 2nd part of the range is a length, not the endpoint. D'oh!

like image 231
Ray Y Avatar asked May 18 '11 23:05

Ray Y


2 Answers

The second parameter passed to NSMakeRange isn't the end location, it's the length of the range.

So the code above tries to find a substring that begins at the first character following <pre> and ends N characters after that, where N is the index of the last character before within the whole string.

Example: in the string "wholeString<pre>test</pre>noMore" ", the first 't' of 'test' has index 16 (first character has index 0), and the final 't' of 'test' has, therefore, index 19. The code above would call NSMakeRange(16, 19), which would include 19 characters, starting with the first 't' of 'test'. But there are only 15 characters, inclusive, from the first 't' of 'test' till the end of the string. Therefore, you get the out of bounds exception.

What you need is to call NSRange with the appropriate length. For the above purpose, it'd be NSMakeRange(match.location+5, match1.location - (match.location+5))

like image 51
executor21 Avatar answered Nov 11 '22 08:11

executor21


Try this

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

In string2, i am calculating the index of the last character

Output :

string 1 = www.google.com/api/123456?google
string 2 = /apple/document1234/
like image 29
vishnu Avatar answered Nov 11 '22 08:11

vishnu