Guys,
How would I go about counting the occurance of a certain character in a given string?
Looking at the string.compare function but cant quite get my head around it.
Thanks
Bob
Printable View
Guys,
How would I go about counting the occurance of a certain character in a given string?
Looking at the string.compare function but cant quite get my head around it.
Thanks
Bob
vb Code:
Dim str As String = "Hi--sdfsdfsdf--" MessageBox.Show(str.Split("-").Length)
You could loop through each character and check:
vb Code:
Dim myString As String = "howmanytimesdoesthelettereoccur" Dim myCOunt As Integer = 0 For Each ch As Char In myString If ch = "e" Then myCOunt += 1 Next MessageBox.Show(myCOunt.ToString)
You could use something like this, be aware that it'll be case sensitive.
vb Code:
Public Function CharCount(ByVal c As Char, ByVal str As String) As Integer Dim intCount As Integer For Each character As Char In str If character = c Then intCount += 1 End If Next Return intCount End Function
This worked for me
vb Code:
Dim str As String = "Hisdf--sddd---fsdf" Dim ncount As Integer = str.Split("-").Length If ncount = 0 Then Console.WriteLine("0 matches") Else Console.WriteLine(String.Concat(ncount - 1, " matches found")) End If
the str.split worked just fine for me.
Thanks