|
-
Feb 1st, 2006, 05:27 PM
#1
Thread Starter
Addicted Member
[RESOLVED] counting how many occurance in a string
How can I find out how many "-" are in a string?
-
Feb 1st, 2006, 05:40 PM
#2
Re: counting how many occurance 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, "-", ""))
-
Feb 1st, 2006, 05:42 PM
#3
Hyperactive Member
Re: counting how many occurance in a string
This might work for you: UBound(Split(MyString, "-"))
-
Feb 1st, 2006, 05:49 PM
#4
Re: counting how many occurance in a string
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
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
casey.
-
Feb 1st, 2006, 06:08 PM
#5
Re: counting how many occurance in a string
 Originally Posted by vbasicgirl
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.
Yep, I just tested it, and it's the fastest:
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
Results in milliseconds:
Replace: 3.57479559248917
Split: 2.29311953450265
CountStr: 0.946257127092146
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|