如何在字符串中查找单词位置(不是字符位置)

时间:2013-08-02 08:45:25

标签: string vba

假设我有一个用空格/连字符分隔的字符串。

EG。抓住这些破碎的翅膀,学会飞翔。

什么vba函数可以找到应该返回的单词的位置为3,而不是11,这是字符位置。

2 个答案:

答案 0 :(得分:1)

一个解决方案(可能有一种更有效的方法)是拆分字符串并迭代返回的数组:

Function wordPosition(sentence As String, searchWord As String) As Long

    Dim words As Variant
    Dim i As Long

    words = Split(sentence, " ")
    For i = LBound(words, 1) To UBound(words, 1)
        If words(i) = searchWord Then Exit For
    Next i

    'return -1 if not found
    wordPosition = IIf(i > UBound(words, 1), -1, i + 1)

End Function

你可以称之为:

Sub AnExample()

    Dim s As String
    Dim sought As String

    s = "Take these broken wings and learn to fly"
    sought = "broken"

    MsgBox sought & " is in position " & wordPosition(s, sought)

End Sub

答案 1 :(得分:1)

assylias提出的解决方案相当不错,只需要很小的调整就可以解决多次问题:

Function wordPosition(sentence As String, searchWord As String) As Long()

    Dim words As Variant
    Dim i As Long

    words = Split(sentence, " ")
    Dim matchesCount As Long: matchesCount = 0
    ReDim matchesArray(UBound(words) + 1) As Long
    For i = LBound(words, 1) To UBound(words, 1)
        If words(i) = searchWord Then
           matchesCount = matchesCount + 1
           matchesArray(matchesCount) = IIf(i > UBound(words, 1), -1, i + 1)
        End If
    Next i

    If (matchesCount > 0) Then
       matchesArray(0) = matchesCount
    End If

    wordPosition = matchesArray

End Function


Sub AnExample()

    Dim s As String
    Dim sought As String

    s = "Take these broken wings and learn to fly and broken again"
    sought = "broken"

    Dim matches() As Long: matches = wordPosition(s, sought)

    If (matches(0) > 0) Then
       Dim count As Integer: count = 0
       Do
          count = count + 1
          MsgBox "Match No. " & count & " for " & sought & " is in position " & matches(count)
       Loop While (count < matches(0))

    End If

End Sub
相关问题