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

Ray*_*y Y 29 cocoa objective-c 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);
Run Code Online (Sandbox Code Playgroud)

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

exe*_*r21 39

传递给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))


vis*_*hnu 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);
Run Code Online (Sandbox Code Playgroud)

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

输出:

string 1 = www.google.com/api/123456?google
string 2 = /apple/document1234/
Run Code Online (Sandbox Code Playgroud)