Adjacent number algorithm grouper

前端 未结 13 1741
不思量自难忘°
不思量自难忘° 2021-02-15 06:55

By which I mean this:

Given the input set of numbers:

1,2,3,4,5 becomes \"1-5\".

1,2,3,5,7,9,10,11,12,14 becomes \"1-3, 5, 7, 9-12, 14\"

This is

13条回答
  •  天涯浪人
    2021-02-15 07:30

    VBA

    Public Function convertListToRange(lst As String) As String
        Dim splLst() As String
        splLst = Split(lst, ",")
        Dim x As Long
        For x = 0 To UBound(splLst)
            Dim groupStart As Integer
            groupStart = splLst(x)
            Dim groupEnd As Integer
            groupEnd = groupStart
            Do While (x <= UBound(splLst) - 1)
                If splLst(x) - splLst(x + 1) <> -1 Then Exit Do
                groupEnd = splLst(x + 1)
                x = x + 1
            Loop
            convertListToRange = convertListToRange & IIf(groupStart = groupEnd, groupStart & ",", groupStart & "-" & groupEnd & ",")
        Next x
        convertListToRange = Left(convertListToRange, Len(convertListToRange) - 1)
    End Function
    

    convertListToRange("1,2,3,7,8,9,11,12,99,100,101")
    Return: "1-3,7-9,11-12,99-101"

提交回复
热议问题