How can I find out how many "-" are in a string?
Printable View
How can I find out how many "-" are in a string?
Code:Dim Str As String
Str = "dfasd-fasd-fasdf-asdfasdf-asdf-asdf--asdf-sad-fasd"
Debug.Print Len(Str) - Len(Replace(Str, "-", ""))
This might work for you: UBound(Split(MyString, "-"))
I am sure i have seen a speed test somewhere and the results showed Instr() within a loop won, correct me if i am wrong. Heres a function
casey.Code:Private Function CountStr(MainString As String, FindString As String) As Long
Dim pos As Long
Do
pos = InStr(pos + 1, MainString, FindString)
If pos Then
CountStr = CountStr + 1
Else
Exit Function
End If
Loop
End Function
Yep, I just tested it, and it's the fastest:Quote:
Originally Posted by vbasicgirl
Results in milliseconds:Code:Option Explicit
Private Sub Form_Load()
Dim Str As String, C As New sTime, Ret As Long
Str = "dfa-sd-fasd-fasdf-asdfasdf-asdf-asdf--asdf-sad-fasd"
Str = Replace(String(200, "~"), "~", Str)
Debug.Print
C.Init
C.StartTime
Ret = Len(Str) - Len(Replace(Str, "-", ""))
C.StopTime
Debug.Print "Replace: " & C.RetTime * 1000
C.StartTime
Ret = UBound(Split(Str, "-"))
C.StopTime
Debug.Print "Split: " & C.RetTime * 1000
C.StartTime
Ret = CountStr(Str, "-")
C.StopTime
Debug.Print "CountStr: " & C.RetTime * 1000
End Sub
Private Function CountStr(MainString As String, FindString As String) As Long
Dim pos As Long
Do
pos = InStr(pos + 1, MainString, FindString)
If pos Then
CountStr = CountStr + 1
Else
Exit Function
End If
Loop
End Function
Replace: 3.57479559248917
Split: 2.29311953450265
CountStr: 0.946257127092146