将数组中的连续/连续数字分组为字符串 [英] Group consecutive/sequential numbers from array into string

查看:66
本文介绍了将数组中的连续/连续数字分组为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 NSNumbers [11,12,13,24,10,25,26,41,30] 的数组并返回一个 NSString,它看起来像以下组:10-13,24-26,30 &41

I'd like to take an array of NSNumbers [11,12,13,24,10,25,26,41,30] and return a NSString that looks like the following Groups: 10-13,24-26,30 & 41

关于我如何实现这一目标的任何方向?我尝试对数组进行排序,然后检查数组中的下一项是否为 +1 以判断它是否连续.但在那之后,当只有 1 个数字(可能发生)或处理最后一个数字时,我不知道如何处理这个数组.也不是用于 NSString 目的的分组.

Any direction on how I can accomplish this? I tried sorting the array, then checking if the next item in the array was +1 to tell if it was consecutive. But after that I did not know how to deal with this array when there was only 1 number (which can happen) or handle the last number either. Nor the grouping for NSString purposes.

推荐答案

NSIndexSet 专门用于此.将您的数字添加到 NSMutableIndexSet,然后使用 enumerateRangesUsingBlock 构建字符串.

NSIndexSet is specialized for that. Add your numbers to NSMutableIndexSet, then use enumerateRangesUsingBlock to build the string.

这篇关于将数组中的连续/连续数字分组为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆