ios - Do these two ranges intersect? If so, how do I know? -
from apple's documentation:
return value range describing intersection of range1 , range2—that is, range containing indices exist in both ranges.
discussion if returned range’s length field 0, 2 ranges don’t intersect, , value of location field undefined.
okay, let's have 2 ranges:
(lldb) p rangeone (nsrange) $3 = location=11, length=4 (lldb) p rangetwo (nsrange) $4 = location=14, length=0
and calculate intersection:
nsrange intersection = nsintersectionrange(rangeone, rangetwo);
the result is:
(lldb) p intersection (nsrange) $5 = location=14, length=0
what supposed that? length zero, location undefined? in case, result expect; can trust it? calculating intersection of ranges 1 range has length of 0 invalid?
you're right. have go documentation. value unusable. hole in api!
as quick thought, similar tommy's answer, here version stronger promise
// nsintersectionrange() except returns location of nsnotfound , // length of nsnotfound when ranges not intersect. static inline nsrange myintersectionrange(nsrange range1, nsrange range2) { if (range1.location == nsnotfound || range1.length == nsnotfound || range2.location == nsnotfound || range2.length == nsnotfound) return nsmakerange(nsnotfound, nsnotfound); nsuinteger begin1 = range1.location; nsuinteger end1 = range1.location + range1.length; nsuinteger begin2 = range2.location; nsuinteger end2 = range2.location + range2.length; if (end1 <= begin2 || end2 <= begin1) return nsmakerange(nsnotfound, nsnotfound); nsuinteger begin = max(begin1, begin2); nsuinteger end = min(end1, end2); return nsmakerange(begin, end - begin); }
the returned value correct answer. have range starting @ location of 14 has length of 0. length of 0 not mean range invalid.
here example using length of 0.
nsstring *x = @"abcdefg"; nsstring *y = @"123"; nsrange range = nsmakerange(4, 0); nsstring *z = [x stringbyreplacingcharactersinrange:range withstring:y]; nslog(@"%@", z);
results in
2014-06-27 14:29:53.610 testapp[10501:303] abcd123efg
in example, length of 0 means location insertion point , not removing of existing string.
if need different answer, calculate yourself.
Comments
Post a Comment