Count Character Occurrences in VB

One option is to utilize a Dictionary object to store the frequency of each character, then iterate through each character in the string and update the corresponding counter. Here is an example code:

Sub CountCharacters()
    Dim str As String
    Dim charCount As New Dictionary
    
    ' 输入字符串
    str = "Hello, World!"
    
    ' 遍历字符串中的每个字符
    For i = 1 To Len(str)
        Dim char As String
        char = Mid(str, i, 1)
        
        ' 如果字符已在字典中存在,则将计数器加1
        If charCount.Exists(char) Then
            charCount(char) = charCount(char) + 1
        Else
            ' 否则初始化计数器为1
            charCount.Add char, 1
        End If
    Next i
    
    ' 输出每个字符出现的次数
    For Each key In charCount.Keys
        Debug.Print key & ": " & charCount(key)
    Next key
End Sub

This code will output each character and the number of times they appear in the string. You can further process the results according to your needs.

bannerAds