首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > VB >

asp 写一个函数,查找子字符串在父字符串首次出现的位置,该怎么处理

2012-02-23 
asp 写一个函数,查找子字符串在父字符串首次出现的位置今天去面试,要求写一个函数,子字符串在父字符串首次

asp 写一个函数,查找子字符串在父字符串首次出现的位置
今天去面试,要求写一个函数,子字符串在父字符串首次出现的位置
  比如:Str1="ABCDEFEF" str2="EF" 返回值5
  和函数instr类似,但要求不能使用instr函数

[解决办法]
其实方法很多

VB code
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
[解决办法]
探讨
引用:
pos = 0
for i = 1 to len(str1) - len(str2)
if mid(str1, i, len(str2)) = str2 then pos = i
next

这个不太准确,Str1="ABCDEFEF" str2="EF" 是正确的 当 Str1="ABCDEFEFFFFFF",str2="EF" 应该返回还是5 ……

热点排行