1,451
社区成员
发帖
与我相关
我的任务
分享
Option Explicit
Dim strA() As String
'采用冒泡排序,从小到大排序
Private Sub Command1_Click()
Dim intP As Integer
Dim intT As Integer
Dim strTemp As String
On Error GoTo errSub
For intP = LBound(strA) To UBound(strA) - 1
For intT = LBound(strA) To UBound(strA) - 1
If Val(strA(intT)) > Val(strA(intT + 1)) Then
'如果前一个元素大于后一个元素,那么交换他们
strTemp = strA(intT)
strA(intT) = strA(intT + 1)
strA(intT + 1) = strTemp
End If
Next intT
Next intP
For intP = LBound(strA) To UBound(strA)
Text2.Text = Text2.Text & strA(intP) & " "
Next intP
Exit Sub
errSub:
Debug.Print Err.Description
End Sub
Private Sub Form_Load()
Dim intP As Integer
Label1.Caption = "排序前:"
Label2.Caption = "排序后:"
Command1.Caption = "排序"
Text1.Text = ""
Text2.Text = ""
strA = Split("1,2,8,7,9,9,8,7,1,2,9,5,0", ",")
For intP = LBound(strA) To UBound(strA)
Text1.Text = Text1.Text & strA(intP) & " "
Next intP
End Sub
d = Array(1, 2, 8, 7, 9, 9, 8, 7, 1, 2, 9, 5, 0)
i = 1
While i <= UBound(d)
If d(i) <> d(i - 1) Then '如果相邻两个数相等,直接向后移一个数,如果不相等则去寻找相等的数
For j = i + 1 To UBound(d)
If d(j) = d(i - 1) Then '如果找到相等的数就交换,并将要比较的数向后移一个数
t = d(i): d(i) = d(j): d(j) = t '交换两数
i = i + 1
End If
Next j
End If
i = i + 1
Wend
For i = 0 To UBound(d)
Debug.Print d(i) & " "; '显示结果
Next i
'调用示例
Private Sub Command1_Click()
Dim str_out As String
Text1.Text = "1,2,8,7,9,9,8,7,1,2,9,5,0"
Process Text1.Text, ",", str_out
End Sub
'str_in 输入输出字符串
'count 要拼接的个数
's_join 用于拼接的字符串
Private Sub MJoin(ByRef str_in As String, ByVal count As Long, ByVal s_join As String)
Dim i As Long
For i = 1 To count
str_in = str_in & s_join
Next
Debug.Print str_in
End Sub
'str_in 要处理的字符串
's_plit 字符串中用的分隔符
'str_out 输出结果
Private Sub Process(ByVal str_in As String, ByVal s_split As String, ByRef str_out As String)
Dim ary() As String
Dim str_old As String
Dim str_new As String
Dim str_temp As String
Dim count As Long
Dim temp_len As Long
'分割字符串
ary = Split(str_in, s_split)
'在字符串的最后添加一个分隔符,这也便于以“元素,”的格式进行替换。
str_old = str_in + s_split
'给要进行替换的str_new赋初始值。
str_new = str_old
'循环变量
Dim i As Long
Loops:
For i = 0 To UBound(ary)
'保存替换前的str_new到str_old
str_old = str_new
'要进行替换的格式“元素,”
str_temp = ary(i) & s_split
'替换字符串
str_new = replace(str_new, str_temp, vbNullString)
'根据替换前后的字符串长度变化,计算出替换了几个元素。
count = (Len(str_old) - Len(str_new)) / Len(str_temp)
'拼接最终结果
Call MJoin(str_out, count, str_temp)
'
temp_len = Len(str_new) - Len(s_split)
If temp_len > 0 Then
'这里的str_new可能已经被替换成空字符串了,因此不能在其左侧取值
str_new = Left(str_new, temp_len)
ary = Split(str_new, s_split)
str_new = str_new + s_split
'数组更新了,需要重新循环
GoTo Loops
End If
Next
str_out = Left(str_out, Len(str_out) - Len(s_split))
Debug.Print str_out
End Sub