2011-04-15 54 views
0

我目前使用下面的代碼取子檢查NSMakeRange能夠採取的範圍或不

NSString *s1 = [stringName substringWithRange: NSMakeRange(0, 2)]; 

NSString *s2 = [stringName substringWithRange: NSMakeRange(2, 4)]; 

NSString *s3 = [stringName substringWithRange: NSMakeRange(6, [stringName length])]; 

在這裏,如何檢查的範圍是有效還是無效,因爲我不能字符串的長度驗證,因爲它可能會有所不同。請幫我解決這個問題。

回答

1

對於s3,你從位置開始,並要求字符串中的字符數一樣多。但是由於你從6號開始,你要求6個字符太多。你需要做的:

NSString *s3 = [stringName substringWithRange: NSMakeRange(6, [stringName length] - 6)]; 
1

隨着蘋果文件說..

substringWithRange:

返回包含在於給定範圍內的接收器的字符的字符串對象。

- (NSString *)substringWithRange:(NSRange)aRange 

人氣指數

A range. The range must not exceed the bounds of the receiver. 

您需要檢查每一次當你構建一個NSMakeRange(),不管你的範圍你的字符串或沒有的長度內指定...通過使用一些if and else條件