asp 写一个函数,查找子字符串在父字符串首次出现的位置
今天去面试,要求写一个函数,子字符串在父字符串首次出现的位置
比如:Str1="ABCDEFEF" str2="EF" 返回值5
和函数instr类似,但要求不能使用instr函数
[解决办法]
其实方法很多
Private Sub Command1_Click() Dim i As Integer, f As Boolean Dim Str1 As String, Str2 As String Str1 = "ABCDEFEFFFFFF" Str2 = "EF" For i = 1 To Len(Str1) If Mid(Str1, i, 2) = Str2 Then f = True Exit For End If Next If f Then MsgBox i Else MsgBox "not find"End SubPrivate Sub Command2_Click() Dim i As Integer, f As Boolean Dim Str1 As String, Str2 As String Dim temp As String Str1 = "ABCDEFEFFFFFF" Str2 = "EF" temp = Str1 For i = 1 To Len(temp) If Left(temp, 2) = Str2 Then f = True Exit For Else If Len(temp) >= 2 Then temp = Right(temp, Len(temp) - 2) End If End If Next If f Then MsgBox (i - 1) * 2 + 1 Else MsgBox "not find" End SubPrivate Sub Command3_Click() Dim i As Integer, f As Boolean Dim Str1 As String, Str2 As String Str1 = "ABCDEFEDFFFFFF" Str2 = "EF" i = Len(Str1) Do While InStrRev(Str1, Str2, i) i = i - 1 f = True Loop If f Then MsgBox i Else MsgBox "not find"End SubPrivate Sub Command4_Click() Dim Str1 As String, Str2 As String Dim temp() As String Str1 = "ABCDEFEFFFFFF" Str2 = "EF" temp = Split(Str1, Str2) If UBound(temp) > 0 Then _ MsgBox Len(temp(0)) + 1 _ Else MsgBox "not find" End Sub
[解决办法]