Reputation: 75
I have a strange issue with substringWithRange function.
I have an NSString with a length of 22.
When I do this:
NSString *result = [myString substringWithRange:NSMakeRange(3, 21)];
Everything is fine. But when I try to get something from middle, like:
NSString *result = [myString substringWithRange:NSMakeRange(11, 14)];
It gives an out of bounds exception.
'NSRangeException', reason: '* -[NSCFString substringWithRange:]: Range or index out of bounds'
So, what's wrong?
Upvotes: 1
Views: 7651
Reputation: 171
NSRange return start position and length. Why length instead end position? Because for example in string Night Café
code [str rangeOfString:@"Café"]
will return length 5, because Café
is in memory will be look like Cafe´
(5 bytes in memory for 4 letter word).
Upvotes: 0
Reputation: 90117
A NSRange is not "from index to index". It is "from index with length".
Why the first one works? I have no idea. I guess in reality your string is not 22 characters long but 24.
Upvotes: 12