计算字符串中每个字符的出现次数

时间:2016-02-07 10:00:16

标签: vb.net string

我尝试使用Google搜索有关此内容的一些信息,但我只发现了一些如何计算要搜索的字符串/字符串的预定义模式的出现次数。我刚刚从我访问过的一些教程/论坛中学到了一些信息。

我想知道是否有替代

的解决方案
Dim qry As System.Collections.Generic.IEnumerable(Of Char) = _
    From c As Char In origStr Select c Distinct

Dim trimmedStr As String = String.Join("", qry)`

删除字符串中的所有重复字符?上面的代码真的????我。这是我用于计算字符串中EACH字符出现次数的代码。

Dim origStr As String

Console.Write("ENTER STRING HERE : ")
origStr = Console.ReadLine()
origStr = LCase(origStr)

' Remove dup chars
Dim qry As System.Collections.Generic.IEnumerable(Of Char) = _
    From c As Char In origStr Select c Distinct
Dim trimmedStr As String = String.Join("", qry)

Dim counts(Len(trimmedStr) - 1) As Integer
Dim cnt As Integer = 0

origStr = Trim(origStr)
trimmedStr = Trim(trimmedStr)

Console.WriteLine(trimmedStr)

For i = 0 To Len(trimmedStr) - 1
    For Each k As Char In origStr
        If (trimmedStr(i) = k) Then
            cnt += 1
        End If
    Next
    counts(i) = cnt
    cnt = 0
    Console.WriteLine(trimmedStr(i) & " => " & counts(i))
Next

Console.ReadKey()

1 个答案:

答案 0 :(得分:0)

此代码计算每个字符在字符串中出现的次数:

Sub Main()
    Dim text As String = "some random text"
    Dim charactersInfo = text.GroupBy(Function(c) c).ToDictionary(Function(p) p.Key, Function(p) p.Count())

    For Each p In charactersInfo
        Console.WriteLine("char:{0}  times:{1}", p.Key, p.Value)
    Next

    Console.ReadLine()
End Sub