objective c compare range intersect

前端 未结 2 566
迷失自我
迷失自我 2021-02-04 11:34

I am trying to find the intersection of 2 number ranges, say for example...

range A is from 10 to 100, range B is from 60 to 70

Is there an easy way without writ

2条回答
  •  迷失自我
    2021-02-04 12:09

    If you have or make NSRange objects, the NSIntersectionRange function will do this for you. Just be sure to check what it returns when there is no intersection.

    NSRange a = NSMakeRange(10, 90);
    NSRange b = NSMakeRange(60, 10);
    NSRange intersection = NSIntersectionRange(a, b);
    if (intersection.length <= 0)
        NSLog(@"Ranges do not intersect");
    else
        NSLog(@"Intersection = %@", NSStringFromRange(intersection));
    

提交回复
热议问题