codes like(x is variable)
dim k as string="5b5" & x & "85"
I want to know how many times "5" appears in k,thanks
Printable View
codes like(x is variable)
dim k as string="5b5" & x & "85"
I want to know how many times "5" appears in k,thanks
try this. i know my way is not best way. but you can refer it.
Code:Dim a As Integer = 0
Dim k As String = "5b585"
For i As Integer = 0 To Len(k) - 1
If k.Substring(i, 1).Contains("5") = True Then
a = a + 1
End If
Next
MsgBox("numbers of 5 is : " & a, MsgBoxStyle.Information, "info")
hey vbsunst
you may use following
Code:Dim sText As String = "5b585"
Dim cMatch as String = "5"
Dim nCount as Integer
For Each sT As String In sText.ToCharArray()
If sT = cMatch Then
nCount=nCount+1
End If
Next
MessageBox.Show(nCount)
I would go for regular expressions
Code:Dim regx As New System.Text.RegularExpressions.Regex("5")
Dim str As String = "1251werwer2225555"
Dim Count As Integer = 0
If regx.IsMatch(str) Then
Count = regx.Matches(str).Count
End If
MessageBox.Show(Count)
Code:Public Function StringCount(ByVal search As String, ByVal find As String) As Integer
If String.IsNullOrEmpty(search) OrElse String.IsNullOrEmpty(find) Then
Return 0
End If
Dim index As Integer = -1
Dim count As Integer = -1
Do
index = search.IndexOf(find, index + 1, StringComparison.CurrentCultureIgnoreCase)
count += 1
Loop While index > -1
Return count
End Function
Oops I accidently posted this twice. Anyway this is just a function that counts the occurrences of a string using the built-in IndexOf and only searches after the last occurrence of the string so it should be pretty efficient. Also it ignores case using the current culture. You could easily add the culture as another parameter.
Edit:
Additionally, this will work for searching whole strings and not just a single character in a string. The functions above look like they will only work for a single character.
Example usage:
Dim count As Integer = StringCount("5b585", "5")
Code:Public Function StringCount(ByVal search As String, ByVal find As String) As Integer
If String.IsNullOrEmpty(search) OrElse String.IsNullOrEmpty(find) Then
Return 0
End If
Dim index As Integer = -1
Dim count As Integer = -1
Do
index = search.IndexOf(find, index + 1, StringComparison.CurrentCultureIgnoreCase)
count += 1
Loop While index > -1
Return count
End Function
You can use LINQ for this to do a count, no need for loops.
EDIT: sorry I did not see you were using VS2005. LINQ is in VS2008.Code:Dim MatchingCharCount = Aggregate C As Char In k _
Where C = "5" _
Into Count()
MessageBox.Show("5 was found: " & MatchingCharCount & " times")