Get the most common character in a string
If you have completed an application and wish to share the complete source/project files with everyone then please post it in here. Source-code files only, no tutorials.
2 posts
Page 1 of 1
This gets the most common character in a string
e.g.
MCC("Apple") will return "p"
e.g.
MCC("Apple") will return "p"
Code: Select all
CharCount Function HereFunction MCC(ByVal iStr As String)
Dim MostUni As Integer = -1
Dim MostVal As Integer = 0
For i = 0 To 65535
If CharCount(iStr, ChrW(i)) > MostVal Then
MostUni = i
MostVal = CharCount(iStr, ChrW(i))
End If
Next
Return ChrW(MostUni)
End Function
This way seems more efficient as it doesn't have to loop for each possible char, rather it only loops for each character in the given string:
Code: Select all
Function commonChar(ByVal input As String) As Char
Dim chars As List(Of Char) = New List(Of Char) 'stores each unique char
Dim counts As List(Of Integer) = New List(Of Integer) 'stores the count of chars at that char's index
For i As Integer = 0 To input.Length - 1
If Not chars.Contains(input(i)) Then
chars.Add(input(i))
counts.Add(0)
Else
counts(chars.IndexOf(input(i))) += 1
End If
Next
Dim highestIndex As Integer = 0
Dim highestCount As Integer = 0
For i As Integer = 0 To chars.Count - 1
If counts(i) > highestCount Then
highestCount = counts(i)
highestIndex = i
End If
Next
Return chars(highestIndex)
End Function
2 posts
Page 1 of 1
Copyright Information
Copyright © Codenstuff.com 2020 - 2023