0

I tried googling some information about this, but I only found some on how to count the occurrences of a pre-defined pattern of a char/string to be searched. I just mixed some of the information I learned from some tutorials/forums I've visited.

I would like to know if there is an alternative solution for the

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)`

to remove all the duplicated characters in a string?The above code really ???? me. This is my code for counting the occurrences of EACH character in a string.

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()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MDB
  • 339
  • 4
  • 19
  • Possible duplicate of *[Count specific character occurrences in string](https://stackoverflow.com/questions/5193893/count-specific-character-occurrences-in-string)* – Peter Mortensen Dec 31 '18 at 23:58

1 Answers1

0

This code counts how many times each character appears in a string:

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
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
shadow
  • 1,883
  • 1
  • 16
  • 24
  • thanks man! this is incredibly short and working! il just have to learn how you do it. thanks again. – MDB Feb 08 '16 at 01:56