Hi all,

Is there a function in vb.net to get how many times string1 is exist in string2?

I had search google and all I found is long code such as this one ( i did not test it) http://www.freevbcode.com/ShowCode.Asp?ID=1025

Is there better way?

Recommended Answers

All 5 Replies

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.
        Loop
        ' 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")
commented: Great Find +8

Sweet! Thanks for the post.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.