在VB中,怎样寻找一个字符串中的第N个指定字符的位置

比如,有这么个字符串str="abs01b902h9dso0h2e70de210j0q"
我只知道用instr函数可以找到第1个0的位置:instr(str,"0")
我想指定第3个0的位置(位于这个字符串的第几个字节),有没有办法呢
如果编写函数或多代码我也会,我就是想了解下有没有一句解决的办法,没有也没关系的

注意函数 FindStrN

Option Explicit

Private Sub Command1_Click()
    Dim s As String
    s = "abs01b902h9dso0h2e70de210j0q"
    
    Dim x As Integer
    
    '第1个"0"的位置
    x = FindStrN(s, "0", 1)
    Print x
    
    '第2个"0"的位置
    x = FindStrN(s, "0", 2)
    Print x
    
    '第3个"0"的位置
    x = FindStrN(s, "0", 3)
    Print x
    
    '第4个"0"的位置
    x = FindStrN(s, "0", 4)
    Print x

    '第5个"0"的位置    
    x = FindStrN(s, "0", 5)
    Print x

    '第6个"0"的位置    
    x = FindStrN(s, "0", 6)
    Print x
    
    '第7个"0"的位置,不存在,返回-1 
    x = FindStrN(s, "0", 7)
    Print x
End Sub


'查找 src 中第n个c出现的位置
'如果没找对,返回-1
Function FindStrN(ByVal src As String, _
    ByVal c As String, _
    ByVal n As Integer) As Integer
    
    Dim i As Integer, m As Integer
    i = InStr(1, src, c)
    m = 0
    Do While i > 0
        m = m + 1
        If m = n Then Exit Do
        i = InStr(i + 1, src, c)
    Loop
    
    If i > 0 And m = n Then
        FindStrN = i
    Else
        FindStrN = -1
    End If
End Function

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-08-05
配合split函数
方法一:
    Debug.Print Len(Split(str, "0")(0)) + 1 + Len(Split(str, "0")(1)) + 1 + Len(Split(str, "0")(2)) + 1
方法二:
    Debug.Print InStr(str, Split(str, "0")(3)) - 1

相似回答