使用substringWithRange提取字符串:给出“索引越界”

时间:2011-05-18 23:32:22

标签: objective-c cocoa nsstring nsrange

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

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:范围的第二部分是长度,而不是端点。 D'哦!

2 个答案:

答案 0 :(得分:39)

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

因此上面的代码尝试在<pre>之后的第一个字符处找到开始的子字符串,然后结束 N个字符,其中N是< strong>整个字符串中最后一个字符的索引。

示例:在字符串"wholeString<pre>test</pre>noMore"中 &#34;,第一个&#39; &#39;测试&#39;索引16(第一个字符有索引0),最后一个字符是&#39; t&#39; &#39;测试&#39;因此,索引19.上面的代码将调用NSMakeRange(16, 19),其中包含19个字符,从第一个字符开始。 &#39;测试&#39;。但是,第一个&#39; t&#39; &#39;测试&#39;直到弦的结尾。因此,您将获得越界异常。

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

答案 1 :(得分:6)

试试这个

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/
相关问题