求助:如何从一个字符串中取得固定长度的所有字符串的组合

goodboyrwy 2003-12-22 02:24:03
例如,一个字符串"abcde",要求取出其中长度为2(也可以为3,4)的任意组合,则结果为aa,ab,ac,ad,ae,ba,bb,bc,bd,...,
如长度为3,则结果为aaa,abb,abc,abd...
...全文
166 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
northwolves 2003-12-22
  • 打赏
  • 举报
回复
Private Sub Command1_Click()
Dim temp
temp = Split(cnm("abcdefg", 5), ",")
For i = 0 To UBound(temp)
List1.AddItem temp(i)
Next
MsgBox List1.ListCount
End Sub



Function cnm(ByVal x As String, ByVal m As Integer) As String '递归代码
x = Trim(x)
Dim temp() As String, temp2() As String, temp3() As String, temp4() As String
Dim counts As Long, i As Long
ReDim temp(Len(x) - 1)
For i = 0 To Len(x) - 1
temp(i) = Mid(x, i + 1, 1)
Next
If m = 1 Then cnm = Join(temp, ",")
If m > 1 Then
temp2 = Split(cnm(x, m - 1), ",")
counts = UBound(temp2)
ReDim temp3(counts)
ReDim temp4(UBound(temp))
For j = 0 To UBound(temp)
For i = 0 To UBound(temp2)
temp3(i) = temp2(i) & temp(j)
Next
temp4(j) = Join(temp3, ",")
Next
cnm = Join(temp4, ",")
Erase temp
Erase temp2
Erase temp4
Erase temp3
End If
End Function



northwolves 2003-12-22
  • 打赏
  • 举报
回复
以前写的递归代码:
Private Sub Command1_Click()

Dim temp
temp = Split(cnm("a,b,c,d,e,f,g", 4), "*")
For i = 0 To UBound(temp)
List1.AddItem temp(i)
Next
MsgBox List1.ListCount
End Sub



Function cnm(ByVal lottery As String, ByVal m As Integer) As String '递归代码
Dim temp, temp2
Dim all As String
Dim num As Integer, i As Long, j As Long
all = lottery
temp = Split(all, ",")
num = UBound(temp) + 1
If m = 1 Then cnm = Replace(all, ",", "*")
If m = 2 Then
For i = 0 To UBound(temp) - 1
For j = i + 1 To UBound(temp)
cnm = cnm & "*" & temp(i) & "," & temp(j)
Next
Next
cnm = Right(cnm, Len(cnm) - 1)
End If
If m > 2 And num >= m Then
all = Left(all, InStrRev(all, ",") - 1)

temp2 = Split(cnm(all, m - 1), "*")
For i = 0 To UBound(temp2)
If temp2(i) <> "" Then temp2(i) = temp2(i) & "," & temp(num - 1)
Next
cnm = Join(temp2, "*")
cnm = cnm & "*" & cnm(all, m)
If Left(cnm, 1) = "*" Then cnm = Right(cnm, Len(cnm) - 1)
If Right(cnm, 1) = "*" Then cnm = Left(cnm, Len(cnm) - 1)
End If
End Function

7,762

社区成员

发帖
与我相关
我的任务
社区描述
VB 基础类
社区管理员
  • VB基础类社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧