【问题标题】:vba sort array by string length and alphabeticallyvba 按字符串长度和字母顺序对数组进行排序
【发布时间】:2016-03-27 20:37:44
【问题描述】:

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

我想要实现的是:

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

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

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

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

【问题讨论】:

    标签: vba sorting


    【解决方案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 行。

    【讨论】:

    • 这个算法正是我所需要的。我必须在pivot 计算中添加括号,因此添加发生在除法之前。我提交了对代码的修改。
    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2021-04-05
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2021-03-16
    相关资源
    最近更新 更多