7,763
社区成员
Private Sub Command1_Click()
Dim allstr As Variant
allstr = Array("白", "白", "晚", "晚", "零", "零", "休", "休")
patstr = Array("白", "晚")
Dim n, m As Integer
n = UBound(allstr) '母串的长度
m = UBound(patstr) '子串的长度
'Print n, m
For i = 0 To n - m
s = i '母串的位置
k = 0 '子串的位置
tt = 0
While (k < m And patstr(k) = allstr(s)) '串匹配算法
k = k + 1 '移动子串的位置
s = s + 1 '移动母串的位置
'If s > n - 1 Then s = 0 如果到了母串末尾则回到串起始位置
Wend
If (k = m) Then
theday = i '保存子串在母串中出现的位置
Text2.Text = theday
Exit For
Else
Text2.Text = "无法匹配"
End If
Next
End Sub
Option Explicit
Private Sub Command1_Click()
Debug.Print searchSrt("白白晚晚零零休休", "白晚") '返回 1
Debug.Print searchSrt("白白晚晚零零休休", "休白") '返回 7
Debug.Print searchSrt("白白晚晚零零休休", "不休") '找不到,返回-1
End Sub
Private Function searchSrt(ByVal str1 As String, ByVal str2 As String) As Long
str1 = str1 & Left(str1, Len(str2) - 1)
searchSrt = InStr(1, str1, str2) - 1
End Function
Dim allstr As Variant
Dim match As Boolean
allstr = Array("白", "白", "晚", "晚", "零", "零", "休", "休")
patstr = Array("休", "白")
Dim n, m As Integer
n = UBound(allstr) '母串的长度
m = UBound(patstr) '子串的长度
For i = 0 To n
s = i '母串的位置
k = 0 '子串的位置
match = True
Do While (k <= m) '循环处理子串
If patstr(k) <> allstr(s Mod (n + 1)) Then
'母串不断+1,下标可能会越界,用Mod
'处理一下,可以重新回到0位置,
'直接变成循环串
match = False '如果不匹配,标false退循环
Exit Do
Else
'如果匹配,游标+1
k = k + 1
s = s + 1
End If
Loop
If match Then Debug.Print i
'不匹配时,已经标false了,match=true代表匹配
Next