How to count occurrences of each letter in a char array with VB.NET

1 Answer

0 votes
Imports System
Imports System.Collections.Generic

Public Class CountLettersInCharArray
	Public Shared Sub Main()
        Dim charArray As Char() = {"V"c, "B"c, "p"c, "r"c, "o"c, "g"c, "r"c, "a"c, "m"c, "m"c, "i"c, "n"c, "g"c}
        Dim letterCount As Dictionary(Of Char, Integer) = New Dictionary(Of Char, Integer)()

        For Each c As Char In charArray
            If letterCount.ContainsKey(c) Then
                letterCount(c) += 1
            Else
                letterCount(c) = 1
            End If
        Next

        For Each item In letterCount
            Console.WriteLine($"Letter {item.Key}: {item.Value} times")
        Next
    End Sub
End Class



' run:
'
' Letter V: 1 times
' Letter B: 1 times
' Letter p: 1 times
' Letter r: 2 times
' Letter o: 1 times
' Letter g: 2 times
' Letter a: 1 times
' Letter m: 2 times
' Letter i: 1 times
' Letter n: 1 times
'  

 



answered Mar 2, 2025 by avibootz
...