iOS开发 升序数组123578转换成1~3,5,7~8

NSArray *arr = @[@"1",@"2",@"3",@"4",@"6",@"7",@"8",@"9",@"12",@"15",@"17",@"19",@"20"];
NSMutableArray *lastArray = [NSMutableArray array];
for (NSInteger i = 0; i < arr.count; i++) {
    NSInteger number = [arr[i] integerValue];
    NSInteger j = 1;
    while (((i + j) < arr.count) && ((number + j) == [arr[i + j] integerValue])) {
        j++;
    }
    
    if (j > 1) {
        [lastArray addObject:[NSString stringWithFormat:@"%@~%@",arr[i],arr[i + j - 1]]];
        i = i + j - 1;
    } else {
        [lastArray addObject:[NSString stringWithFormat:@"%@",arr[i]]];
    }
}
NSLog(@"%@",lastArray);

推荐阅读更多精彩内容