0

我想计算给定字符串/句子中特定单词的出现次数。我已经尝试过使用下面的代码,但它不起作用。

Sub main()
   MainStr = " yes no yes yes no yes no "
   Str1 = " yes "
   MsgBox UBound(Split(MainStr, Str1))
End Sub

在上面的代码中,我想从 MainStr 中搜索 Str1。在大多数博客中,人们都给出了使用“拆分”功能来计算出现次数的解决方案。但是当搜索词紧随其后时,它不会给出正确的结果。

在上面的场景中,搜索词是“是”,它出现在第三和第四位。

上面的代码将在以下情况下给出正确的结果, MainStr = " yes no yes no yes no yes " Str1 = " yes "

请帮助我,因为我已经尝试/搜索了很多以找到解决方案。

谢谢 !

4

2 回答 2

3

你可以试试:

HowManyOccurrences = ubound(split(whole_string, search_string))

它使用 search_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)
于 2013-10-15T22:06:36.833 回答
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)
于 2013-10-15T22:02:28.127 回答