我有一個字符串(例如:"Hello there. My name is John. I work very hard. Hello there!"
),我試圖找到字符串"hello there"
的出現次數。到目前爲止,這是我的代碼有:如何找到字符串中子字符串的出現次數vb.net
Dim input as String = "Hello there. My name is John. I work very hard. Hello there!"
Dim phrase as String = "hello there"
Dim Occurrences As Integer = 0
If input.toLower.Contains(phrase) = True Then
Occurrences = input.Split(phrase).Length
'REM: Do stuff
End If
不幸的是,這行代碼,似乎做的每一次拆分字符串它看到的phrase
的第一個字母,在這種情況下,h
。所以,而不是我希望的結果Occurrences = 2
,我實際上得到一個更大的數字。我知道計算一個字符串中分割的次數是一個可怕的方式去做這件事,即使我確實得到了正確的答案,所以有人可以幫助我並提供一些幫助嗎?
問題不是很好形成。如果您使用vb.net進行標記,則Split函數將接受一個字符串,而不僅僅是一個字符。因此,在你的情況下它會是3,因爲你忘了減1。參考:https://msdn.microsoft.com/en-us/library/system.string.split%28v=vs.110%29.aspx – Gaucho