2
A
回答
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
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
相關問題
- 1. 如何找到字符串放在字符串中的位置?
- 2. Scheme:如何找到一個字符串中的字符位置
- 3. 如何找到字符串中特定字符的位置
- 4. 查找字符串中的單詞位置(不是字符位置)
- 5. Python在字符串中找到位置
- 6. 如何使用charAt查找字符串中字符的位置
- 7. 字符串的位置找到字符串
- 8. 找到一個字符在字符串中的位置?
- 9. 字符在字符串中當前位置左側的位置
- 10. 找到字符串時輸入位置
- 11. 如何找到字符串數組中特定字符串的位置?
- 12. 如何從字符串中找到子字符串列表的位置?
- 13. 如何找到字符串在C++中的子串的位置?
- 14. 查找字符串中最後一位數字的位置
- 15. 在C字符串中查找位置
- 16. 如何在給定的文檔中找到字符串的位置或位置
- 17. 由字符位置掰開字符串
- 18. MySQL查找字符串內字符串的結束位置
- 19. 如何找到一個字符的位置在一個字符串中PHP
- 20. 在字符串中查找字符的位置
- 21. 查找字符串中字符的位置
- 22. 查找字符串中字符的位置
- 23. 使用dplyr mutate查找字符串中的字符位置
- 24. 查找字符串位置 - Python的
- 25. 如何找到字符串中的單詞的位置?
- 26. Python找到字符串中最後一個數字的位置
- 27. 如何找到列表中的位置字符串?
- 28. 如何僅刪除位置字符串中的字符?
- 29. 如何從某個位置的字符串中刪除字符?
- 30. 如何更改字符串中字符的位置?
Tha NKS。該函數可以正常工作,但如果字符串中有多個單詞的實例,該函數將無法檢測到相應的位置。 – SanilB
你可以'如果strcomp(left $(words(i),len(searchword)),searchword,vbtextcompare)= 0,那麼退出for'這會使''broken''也匹配''BROKK?' –
@AlexK 。我不完全確定你的意思。同時請記住,您可以通過依賴LCase獲得與您建議的結果相同的結果。 OP並不是說他期望「破」與「BRoken」相等,而是在給定的字符串(可能不止一個)中找到所有現有的「破」字。我想唯一的方法來實現這個(使用這個函數),將所有的出現存儲在一個數組中,並返回它(而不是一個單一的位置),在我的答案中提供了代碼(這只是這個更新版本碼)。 – varocarbas