2011-05-18 101 views
28

當我嘗試從較大的字符串中提取字符串時,它給了我一個範圍或索引超出範圍的錯誤。我可能忽略了一些非常明顯的東西。謝謝。使用substringWithRange提取字符串:給出「索引超出範圍」

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

你應該把你的「解決方案」作爲回答,並接受它。 – LucasTizma 2011-05-18 23:45:06

回答

36

傳遞給NSMakeRange的第二個參數不是結束位置,而是該範圍的長度。

所以上面的代碼試圖找到的子串的是在第一個字符以下<pre>之後 N個字符結束,其中N是之前的最後一個字符的索引整個字符串內開始

實施例:字符串"wholeString<pre>test</pre>noMore" 」中,‘測試’的第一‘T’具有索引16(第一個字符的索引爲0),和‘測試’的最後的‘T’具有,因此,索引19。上面的代碼將調用NSMakeRange(16, 19),它將包含19個字符,從'test'的第一個't'開始,但從'test'的第一個't'到字符串的結尾只有15個字符因此,你越界異常。

你需要的是調用NSRange與合適的長度。爲達到上述目的,它會是 NSMakeRange(match.location+5, match1.location - (match.location+5))

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

包含字符串,我計算的最後一個字符的索引

輸出:

string 1 = www.google.com/api/123456?google 
string 2 = /apple/document1234/