Tuesday, 17 January 2012

String Pattern Count

For this we need 2 controls.        1. Label                 2.Button


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Label1.Text = CountStringOccurrences("jfasjdj hgsdfassfasf iguFasdf iufaysdf ", "fas")
    End Sub


Public Shared Function CountStringOccurrences(ByVal text As String, ByVal pattern As String) As Integer
        'Loop through all instances of the string 'text'
        Dim count As Integer = 0
        Dim i As Integer = 0
        While (InlineAssignHelper(i, text.IndexOf(pattern, i))) <> -1  'InlineAssignHelper
            i += pattern.Length
            count += 1
        End While
        Return count
    End Function

Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
        target = value
        Return value
    End Function                                                                  

No comments:

Post a Comment