vba按字符串长度和字母顺序排序数组

时间:2016-03-27 20:37:45

标签: vba sorting

说使用Split函数后我们有一个字符串数组,如ArrStr = ("this","is","a","random","phrase")

我想要实现的目标是:

  • 首先,ArrStr按数组项的字符串长度排序,即ArrStr = ("a","is","this","random","phrase"),因为len(“a”)= 1,len(“is”)= 2 .. .etc

  • 第二,ArrStr然后再次排序,但这次按字母顺序保留第一个按长度排序,即ArrStr = ("a","is","this","phrase","random"),字符串“短语”代替字符串“随机”,因为它以“p”开头,我们都知道字母“p”出现在英文字母“r”之前。

在排序过程中,文本被视为不区分大小写

关于如何实现这一目标的任何有效想法?

1 个答案:

答案 0 :(得分:1)

任何排序算法都可行 - 您需要做的就是根据自定义条件进行项目比较:

Private Function SortCompare(one As String, two As String) As Boolean
    Select Case True
        Case Len(one) < Len(two)
            SortCompare = True
        Case Len(one) > Len(two)
            SortCompare = False
        Case Len(one) = Len(two)
            SortCompare = LCase$(one) < LCase$(two)
    End Select
End Function

例如,使用快速排序:

Public Sub CustomQuickSort(list() As String, first As Long, last As Long)
    Dim pivot As String
    Dim low As Long
    Dim high As Long

    low = first
    high = last
    pivot = list((first + last) \ 2)

    Do While low <= high
        Do While low < last And SortCompare(list(low), pivot)
            low = low + 1
        Loop
        Do While high > first And SortCompare(pivot, list(high))
            high = high - 1
        Loop
        If low <= high Then
            Dim swap As String
            swap = list(low)
            list(low) = list(high)
            list(high) = swap
            low = low + 1
            high = high - 1
        End If
    Loop

    If (first < high) Then CustomQuickSort list, first, high
    If (low < last) Then CustomQuickSort list, low, last
End Sub

用法示例:

Public Sub SampleCode()
    Dim sample() As String
    sample = Split("this,is,a,random,phrase", ",")
    CustomQuickSort sample, LBound(sample), UBound(sample)

    Dim i As Integer
    For i = LBound(sample) To UBound(sample)
        Debug.Print sample(i)
    Next i
End Sub

如果您希望按降序排序,请交换SortCompare = TrueSortCompare = False行。