我有一个字符串(例如: "Hello there. My name is John. I work very hard. Hello there!"
),我试图找到字符串 "hello there"
的出现次数.到目前为止,这是我拥有的代码:
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
我所希望的,实际上我得到了一个更大的数字。我知道计算字符串中的分割数是一种可怕的方法,即使我确实得到了正确的答案,所以有人可以帮助我并提供一些帮助吗?
最佳答案
您可以创建一个 Do until 循环,该循环在整数变量等于您要检查的字符串的长度时停止。如果该短语存在,则增加出现次数并将该短语的长度加上找到它的位置添加到游标变量中。如果找不到该短语,则您已完成搜索(没有更多结果),因此将其设置为目标字符串的长度。为了不计算多次相同的出现,只检查从游标到循环中目标字符串的长度 (strCheckThisString)。
Dim input As String = "hello there. this is a test. hello there hello there!"
Dim phrase As String = "hello there"
Dim Occurrences As Integer = 0
Dim intCursor As Integer = 0
Do Until intCursor >= input.Length
Dim strCheckThisString As String = Mid(LCase(input), intCursor + 1, (Len(input) - intCursor))
Dim intPlaceOfPhrase As Integer = InStr(strCheckThisString, phrase)
If intPlaceOfPhrase > 0 Then
Occurrences += 1
intCursor += (intPlaceOfPhrase + Len(phrase) - 1)
Else
intCursor = input.Length
End If
Loop
关于vb.net - 如何查找字符串中子字符串的出现次数 vb.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14286505/