我想计算给定字符串/句子中特定单词的出现次数。我已经尝试使用下面的代码,但它不起作用。
Sub main()
MainStr = " yes no yes yes no yes no "
Str1 = " yes "
MsgBox UBound(Split(MainStr, Str1))
End Sub
在上面的代码中,我想从MainStr中搜索Str1。在大多数博客中,人们给出了使用“拆分”功能来计算事件的解决方案。但是当搜索词紧跟在彼此之后,它将无法给出正确的结果。
在上面的场景中,搜索词是“是”&它将在第3&第四名。
以下代码将为以下情况提供正确的结果, MainStr =“是否否是否是否是” Str1 =“是”
请帮我解决这个问题因为我已经尝试/搜索了很多以找到解决方案。
谢谢!
答案 0 :(得分:3)
您可以尝试:
HowManyOccurrences = ubound(split(whole_string, search_string))
使用search_string作为分隔符将whole_string拆分为和数组,返回数组中元素的数量。
你最需要循环(或提出递归正则表达式,然后计算捕获或其他东西):
Dim whole_string As String
Dim search_string As String
Dim temp As String
Dim ctr As Integer
whole_string = "yes no yes yes no yes no "
search_string = "yes"
temp = whole_string
ctr = 0
While (InStr(1, temp, search_string) > 0)
temp = Replace(temp, search_string, "", 1, 1)
ctr = ctr + 1
Wend
MsgBox (ctr)
答案 1 :(得分:0)
I beleive you will need a loop, Not sure you can accomplish this with just 1 line of code, maybe I am wrong
Dim s As String
Dim searchWord As String
Dim iSearchIndex As Integer
Dim iCounter
searchWord = "YES"
s = "yes no yes yes no no yes yes yes no yes"
Do While True
'get the location of the search word
iSearchIndex = InStr(1, UCase(s), "YES")
'check to make sure it was found
If iSearchIndex > 0 Then
'create a string removing the found word
s = Mid(s, iSearchIndex + Len(searchWord))
'add 1 to our counter for a found word
iCounter = iCounter + 1
Else
Exit Do 'nothing found so exit
End If
Loop
MsgBox CStr(iCounter)