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

更新:範囲の2番目の部分は長さであり、端点ではありません。D'oh!

4

2 に答える 2

41

NSMakeRangeに渡される2番目のパラメーターは、終了位置ではなく、範囲の長さです。

したがって、上記のコードは、後続の最初の文字で始まり、その後にN文字<pre>終わる部分文字列を見つけようとします。ここで、Nは、文字列全体の前の最後の文字のインデックスです

例:文字列"wholeString<pre>test</pre>noMore" "では、'test'の最初の't'はインデックス16(最初の文字はインデックス0)を持ち、'test'の最後の't'はインデックス19を持ちます。したがって、上記のコードはNSMakeRange(16, 19)、を呼び出します。これには、「test」の最初の「t」から始まる19文字が含まれますが、「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 に答える