[英]how do you find a word in a sentence and return its positions in visual basic
例如“我帶着她的狗走到我的狗跳進的湖邊”我希望程序告訴我在我的例子中位置 4 和 11 等位置
這個功能應該工作:
Private Function FindWord(Text As String, Word As String) As List(Of Integer)
Dim results As New List(Of Integer)
Dim target As String = Word.ToLower
Dim p() As String = Split(Text.ToLower, " ")
For i As Integer = 0 To p.Length - 1
If p(i).Contains(target) Then results.Add(i + 1)
Next
Return results
End Function
它將輸入解析為“單詞”數組。 然后它使用 contains 函數來處理標點符號。
你可以這樣稱呼它:
Dim r As List(Of Integer) = FindWord("my walked her dog down to the lake which my dog jumped in", "dog")
您必須考慮如果字符串包含 doghouse 會發生什么。 如果你不想打那個,那么這將不得不修改。 在這種情況下,您將需要過濾掉標點符號並在其余部分中尋找完全匹配的內容。
Private Function FindWord(Text As String, Word As String) As List(Of Integer)
Dim results As New List(Of Integer)
Dim target As String = Word.ToLower
Dim rgx As New Regex("[^a-z]")
Dim p() As String = Split(Text.ToLower, " ")
For i As Integer = 0 To p.Length - 1
If rgx.Replace(p(i), "") = target Then results.Add(i + 1)
Next
Return results
End Function
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.