由于 VBScript 没有原生排序,因此需要朋友的帮助。在您的情况下 - 由于您的排序标准更复杂 - 朋友不应该是 .Net 的 ArrayList、JScript 的排序或 sort.exe(在此处介绍),而是断开连接的 ADO 记录集:
Const adInteger = 3 ' 00000003
Const adVarChar = 200 ' 000000C8
Dim sInp : sInp = "this is an example of a description"
Dim aInp : aInp = Split(sInp)
WScript.Echo "A:", Join(aInp)
Dim oRS : Set oRS = CreateObject("ADODB.Recordset")
oRS.Fields.Append "Word", adVarChar, 50
oRS.Fields.Append "Length", adInteger
oRS.Open
Dim sWord
For Each sWord In aInp
oRS.AddNew
oRS.Fields("Word").value = sWord
oRS.Fields("Length").value = Len(sWord)
oRS.UpDate
Next
oRS.Sort = "Length DESC, Word"
Dim aTable : aTable = oRS.GetRows()
ReDim aOut(UBound(aTable, 2))
Dim i
For i = 0 To UBound(aOut)
aOut(i) = aTable(0, i)
Next
WScript.Echo "B:", Join(aOut)
输出:
A: this is an example of a description
B: description example this an is of a
背景从这里开始。
添加 - 对于 ArrayList 爱好者:
如果您的数据本质上是表格的(排序标准涉及元素的多个方面/属性),则断开连接的记录集应该是您的首选。
VBScript 中的 ArrayList 排序仅适用于简单的情况,因为 - AFAIK - 您不能将比较函数传递给 sort 方法。请证明我错了!
如果您必须使用 ArrayList 进行更复杂的排序,请考虑
Schwartzian 变换:
- 准备定制的临时数据以方便比较
- 种类
- 恢复原始数据
在代码中:
Const csSep = "|"
Const cnMax = 100
Dim sInp : sInp = "this is an example of a description"
Dim aInp : aInp = Split(sInp)
WScript.Echo "A:", Join(aInp)
Dim oNAL : Set oNAL = CreateObject( "System.Collections.ArrayList" )
Dim oSB : Set oSB = CreateObject( "System.Text.StringBuilder" )
Dim sWord
For Each sWord In aInp
oSB.AppendFormat_3 "{0,4}{1}{2}", 100 - Len(sWord), csSep, sWord
sWord = oSB.ToString()
oSB.Length = 0
oNAL.Add sWord
Next
oNAL.Sort
ReDim aOut(oNAL.Count - 1)
Dim i
For i = 0 To UBound(aOut)
aOut(i) = Split(oNAL(i), csSep)(1)
Next
WScript.Echo "B:", Join(aOut)
输出:
A: this is an example of a description
B: description example this an is of a