Skip to content

Instantly share code, notes, and snippets.

@wokalski
Created July 17, 2012 16:21
Show Gist options
  • Save wokalski/3130403 to your computer and use it in GitHub Desktop.
Save wokalski/3130403 to your computer and use it in GitHub Desktop.
NSRangeContainsRange - check if NSRange contains the other NSRange :)
bool NSRangeContainsRange (NSRange range1, NSRange range2) {
BOOL retval = NO;
if (range1.location <= range2.location && range1.location+range1.length >= range2.length+range2.location) {
retval = YES;;
}
return retval;
}
@thirtified
Copy link

Btw, there is also

NSIntersectionRange(range1, range2).length == range2.length;

@ferostabio
Copy link

Actually, if you simply want to know if a range contains another one, you have to do

NSIntersectionRange(range1, range2).length > 0

@thirtified's will not work, since a range might container another one regardless of the length of the second one and NSIntersectionRange returns a range with a length of 0 if false (if range1 doesn't intersects with range2).

@thirtified
Copy link

Ok, I see: my previously posted line fails in the case that the second range has length zero and it's location is not within the first range, thanks for pointing that out.

To fix this one would have to add another check (assuming that a range with length zero can actually be considered "contained" in another range):

NSIntersectionRange(range1, range2).length == range2.length || NSLocationInRange(range2.location, range1);

which is not really simpler than the original solution.

So, I conclude with a different attempt which in my opinion is slightly more readable than the original one:

NSLocationInRange(range2.location, range1) && NSLocationInRange(NSMaxRange(range2), range1);

Note that both solutions will return false whenever range1.length == 0, because a range with size zero cannot contain any other range (not even a location). The original implementation will return true for this case if range1 == range2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment