2013-08-02 83 views

回答

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 

你可以稱它爲ILKE這樣的:

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 
+0

Tha NKS。該函數可以正常工作,但如果字符串中有多個單詞的實例,該函數將無法檢測到相應的位置。 – SanilB

+0

你可以'如果strcomp(left $(words(i),len(searchword)),searchword,vbtextcompare)= 0,那麼退出for'這會使''broken''也匹配''BROKK?' –

+0

@AlexK 。我不完全確定你的意思。同時請記住,您可以通過依賴LCase獲得與您建議的結果相同的結果。 OP並不是說他期望「破」與「BRoken」相等,而是在給定的字符串(可能不止一個)中找到所有現有的「破」字。我想唯一的方法來實現這個(使用這個函數),將所有的出現存儲在一個數組中,並返回它(而不是一個單一的位置),在我的答案中提供了代碼(這只是這個更新版本碼)。 – varocarbas

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 
相關問題