开发者

Check NSMakeRange is Able to take range or Not

I am currently using the below code to take the substring

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

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

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

Here, how to check the range is valid or not because i am not able to length of string to validat开发者_运维百科e because it may differ on time. Please help me in this issue..


For s3, you're starting at position and ask for exactly as many characters as there are in the string. But since you're starting at position 6, you're asking for 6 characters too many. You need to do:

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


As the apple documentation says ..

substringWithRange:

Returns a string object containing the characters of the receiver that lie within a given range.

- (NSString *)substringWithRange:(NSRange)aRange

aRange

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

You need to check every time when you construct an NSMakeRange(), whether the Range you specified within the length of your String OR not ... by Using some if and else condition

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜