Arrays 在VBS中对数字数组进行排序
我想在vbs中对数组进行排序,因此数组中包含的数字是递增的。我正在从文本文件中读取数字Arrays 在VBS中对数字数组进行排序,arrays,sorting,vbscript,Arrays,Sorting,Vbscript,我想在vbs中对数组进行排序,因此数组中包含的数字是递增的。我正在从文本文件中读取数字 Sub Main() Dim Werte(10) Dim c Dim fso Set fso = CreateObject("Scripting.FileSystemObject") Set c = fso.Drives Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("Y:\Ben
Sub Main()
Dim Werte(10)
Dim c
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Set c = fso.Drives
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile("Y:\Benutzer\Desktop\Werte.txt",1)
Dim strLine
Dim i
i=0
do while not objFileToRead.AtEndOfStream
strLine = objFileToRead.ReadLine()
Werte(i)=strLine
i=i+1
loop
objFileToRead.Close
Set objFileToRead = Nothing
for x=LBound(Werte) To UBound(Werte) - 1 Step 1
for j= 0 to UBound(Werte)-1
if Werte(j)>Werte(j+1) then
temp=Werte(j+1)
Werte(j+1)=Werte(j)
Werte(j)=temp
end if
next
next
PATH="Y:\Benutzer\Desktop\Werte_sortiert.txt"
Array_ToTextFile Werte,PATH
End Sub
Function Array_ToTextFile(a,path)
Const ForWriting = 2
Dim fso
Dim writer
Dim i
Set fso = CreateObject("Scripting.FileSystemObject")
Set writer = fso.OpenTextFile(path,ForWriting,True)
For i = lbound(a) to ubound(a)
writer.writeline a(i)
Next
writer.close
End Function
Main
文本文件如下所示:
十,
9
8.
7.
6.
5.
4.
3.
2.
1.
0
结果如下所示:
0
1.
10
2.
3.
4.
5.
6.
7.
8.
九,
数字10应位于末尾,但在排序后位于第3个位置。非常感谢您的帮助。问题是您正在进行字符串比较,而不是数字比较。如果将第21行更改为:
if Werte(j)>Werte(j+1) then
致:
它将正确排序。虽然回答了这个问题,但我只想补充一点,您确实不需要阅读每一行。您可以预先读取整个文件,然后在vbCrLf delim上拆分数据。也可以使用System.Collections.ArrayList并将每一行添加到排序数组中。
if Int(Werte(j))>Int(Werte(j+1)) then