how to find the number of occurrences of a substring within a string vb.net

后端 未结 12 2030
逝去的感伤
逝去的感伤 2020-12-06 02:14

I have a string (for example: \"Hello there. My name is John. I work very hard. Hello there!\") and I am trying to find the number of occurrences of the string

12条回答
  •  无人及你
    2020-12-06 02:51

    You could create a recursive function using IndexOf. Passing the string to be searched and the string to locate, each recursion increments a Counter and sets the StartIndex to +1 the last found index, until the search string is no longer found. Function will require optional parameters Starting Position and Counter passed by reference:

    Function InStrCount(ByVal SourceString As String, _
                        ByVal SearchString As String, _
                        Optional ByRef StartPos As Integer = 0, _
                        Optional ByRef Count As Integer = 0) As Integer
        If SourceString.IndexOf(SearchString, StartPos) > -1 Then
            Count += 1
            InStrCount(SourceString, _
                       SearchString, _
                       SourceString.IndexOf(SearchString, StartPos) + 1, _
                       Count)
        End If
        Return Count
    End Function
    

    Call function by passing string to search and string to locate and, optionally, start position:

    Dim input As String = "Hello there. My name is John. I work very hard. Hello there!"
    Dim phrase As String = "hello there"
    Dim Occurrences As Integer
    
    Occurrances = InStrCount(input.ToLower, phrase.ToLower)
    

    Note the use of .ToLower, which is used to ignore case in your comparison. Do not include this directive if you do wish comparison to be case specific.

提交回复
热议问题