How to pull an integer value from NSRange?
Asked Answered
I

2

7

I have an NSRange and need to break a string into two substrings on either side of this NSRange. How do I get an integer value (like the index) out of an NSRange?

Interlay answered 27/8, 2012 at 14:50 Comment(0)
D
4

NSRange struct consists of two integers - the location and the length.

typedef struct _NSRange {
    NSUInteger location;
    NSUInteger length;
} NSRange;

It looks like location and location+length are the two expressions that you are looking for - the ranges for the left and right substring are as follows:

NSRange prefixRange = NSMakeRange(0, myRange.location);
NSUInteger pos =myRange.location+myRange.length;
NSRange suffixRange = NSMakeRange(pos, myString.length - pos);
Desantis answered 27/8, 2012 at 14:52 Comment(0)
J
0

I know this question is old, but in Swift 4 (and perhaps earlier) there are new upperBound and lowerBound convenience properties on NSRange:

print(myRange) // Range: {13, 4}    
range.lowerBound // 13
range.upperBound // 17

Hopefully that helps someone else.

Jordon answered 16/11, 2017 at 4:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.