9 Years
Discussion Span
Last Post by samir_ibrahim

Not really. That code is not only functional, but also makes use of some techniques to reduce the load on the processor and make the program run faster.... so, truthfully, that code is about as good as you are going to get. Granted, I suppose there should be a method in the string class to return that kind of information, but there simply isn't.


If you take the remarks out it is not that long.
This might be a bit shorter:

Dim MyString As String = "now is the now is the not now is th"
    Dim str As String = "now is"  ' the search string
    Dim count As Integer = 0      ' how many times the search string is in MyString 
    Dim index As Integer = 0      ' where you are currently looking

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' First find out if the string is in MyString. Index starts at 0 so we start at the begining of the string
        ' The IndexOf returns the position of the search string. If it is greater that -1 then it was found.
        Do While MyString.IndexOf(str, index) >= 0
            ' it was found so increment the count
            count += 1
            ' get the new index which is where the current occurance is and add one to it so we get past the current
            index = MyString.IndexOf(str, index) + 1
            ' loop back until it can't find any more.
        ' show the count
        MessageBox.Show("Number of occurances = " & count.ToString)
    End Sub

Thank you all for your response.

I had found t hi s code which is very short 3 lines if you remove the first 3 lines which are for explanatory purpose

Dim SearchFor, SearchIn As String
SearchIn = "She sells sea shells on the sea shore"
SearchFor = "sea"
Dim rex As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex(SearchFor)
Dim count As Integer = rex.Matches(SearchIn).Count
MessageBox.Show(SearchFor & " occurs " & count & " times")
Votes + Comments
Great Find
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.