【问题标题】:Extracting a string with substringWithRange: gives "index out of bounds"使用 substringWithRange 提取字符串:给出“索引超出范围”
【发布时间】:2011-08-28 11:25:45
【问题描述】:

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

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

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

【问题讨论】:

  • 你应该把你的“解决方案”作为答案并接受它。

标签: objective-c cocoa nsstring nsrange


【解决方案1】:

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

所以上面的代码试图找到一个子字符串,它开始&lt;pre&gt;之后的第一个字符处,结束之后的N个字符,其中N是整个字符串中最后一个字符的索引

示例:在字符串"wholeString&lt;pre&gt;test&lt;/pre&gt;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))

【讨论】:

    【解决方案2】:

    试试这个

    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/
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 2017-02-03
      • 2016-02-19
      • 2012-03-02
      • 2016-02-10
      相关资源
      最近更新 更多