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

后端 未结 12 2031
逝去的感伤
逝去的感伤 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:50

    You can create a Do Until loop that stops once an integer variable equals the length of the string you're checking. If the phrase exists, increment your occurences and add the length of the phrase plus the position in which it is found to the cursor variable. If the phrase can not be found, you are done searching (no more results), so set it to the length of the target string. To not count the same occurance more than once, check only from the cursor to the length of the target string in the Loop (strCheckThisString).

        Dim input As String = "hello there. this is a test. hello there hello there!"
        Dim phrase As String = "hello there"
        Dim Occurrences As Integer = 0
    
        Dim intCursor As Integer = 0
        Do Until intCursor >= input.Length
    
            Dim strCheckThisString As String = Mid(LCase(input), intCursor + 1, (Len(input) - intCursor))
    
            Dim intPlaceOfPhrase As Integer = InStr(strCheckThisString, phrase)
            If intPlaceOfPhrase > 0 Then
    
                Occurrences += 1
                intCursor += (intPlaceOfPhrase + Len(phrase) - 1)
    
            Else
    
                intCursor = input.Length
    
            End If
    
        Loop
    

提交回复
热议问题