30

当我尝试从较大的字符串中提取字符串时,它会给我一个范围或索引超出范围的错误。我可能在这里忽略了一些非常明显的东西。谢谢。

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

更新:范围的第二部分是长度,而不是端点。哦!

4

2 回答 2

41

传递给 NSMakeRange 的第二个参数不是结束位置,而是范围的长度。

所以上面的代码试图找到一个从第一个字符开始<pre>并在其后结束N 个字符的子字符串,其中 N 是整个字符串中之前最后一个字符的索引

示例:在字符串"wholeString<pre>test</pre>noMore" " 中,'test' 的第一个 't' 的索引为 16(第一个字符的索引为 0),因此 'test' 的最后一个 't' 的索引为 19。上面的代码将调用NSMakeRange(16, 19),这将包括 19 个字符,从 'test' 的第一个 't' 开始。但是从 'test' 的第一个 't' 到字符串的结尾,只有 15 个字符,包括在内。因此,你得到了边界异常。

您需要的是使用适当的长度调用 NSRange。出于上述目的,它会是 NSMakeRange(match.location+5, match1.location - (match.location+5))

于 2011-05-18T23:53:15.513 回答
7

尝试这个

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

在 string2 中,我正在计算最后一个字符的索引

输出 :

string 1 = www.google.com/api/123456?google
string 2 = /apple/document1234/
于 2015-06-04T06:34:29.993 回答