|
本帖最后由 todaynew 于 2011-4-28 20:28 编辑
编写自定义函数时,一般需要找到所需功能的核心算法,这个算法可先从一个特例开始进行编写。中心开花,逐步抽象,递次外延,直到获得满足功能需求的完整代码。下面以版友123xiaoniu同志昨日所问字符串排序问题为例,说明函数编写的过程。
第一步 先做字符串第一位的排序,基本思路为:将第一位的字符顺序向后逐个比较,取得最小值的字符,并将其排列到第一位。那么函数可写为:
Function OrderStr(str As String) As String
Dim s As String
Dim j As Long
Dim n As Long
s = Mid(str, 1, 1)
For j = 1 To Len(str)
If Mid(str, j, 1) < s Then s = Mid(str, j, 1): n = j '计算最小值及其位置。
Next
str = s & Replace(str, s, "", 1, 1) '排序
OrderStr = str
End Function
第二步 做第一位到倒数第二位的循环比较排序。函数可写为:
Function OrderStr(str As String) As String
Dim s As String
Dim i As Long, j As Long
Dim n As Long
For i = 1 To Len(str) - 1
s = Mid(str, i, 1)
For j = i + 1 To Len(str)
If Mid(str, j, 1) < s Then s = Mid(str, j, 1): n = j
Next
str = Mid(str, 1, i - 1) & s & Replace(str, s, "", i, 1)
Next
OrderStr = str
End Function
第三步 做可选择顺序和逆序的排序函数
Function OrderStr(str As String, B As Long) As String
'功能:字符串排序
'参数:str--源字符串,B=1 降序 B=2 升序
Dim s As String
Dim i As Long, j As Long
Dim n As Long
For i = 1 To Len(str) - 1
s = Mid(str, i, 1)
For j = i + 1 To Len(str)
Select Case B
Case 1
If Mid(str, j, 1) < s Then s = Mid(str, j, 1): n = j
Case 2
If Mid(str, j, 1) > s Then s = Mid(str, j, 1): n = j
End Select
Next
str = Mid(str, 1, i - 1) & s & Replace(str, s, "", i, 1)
Next
OrderStr = str
End Function
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?注册
x
|