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

67,087

Solution 1

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

Solution 2

Yet another idea:

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 = (input.Length - input.Replace(phrase, String.Empty).Length) / phrase.Length

You just need to make sure that phrase.Length > 0.

Solution 3

the best way to do it is this:

Public Function countString(ByVal inputString As String, ByVal stringToBeSearchedInsideTheInputString as String) As Integer
    Return System.Text.RegularExpressions.Regex.Split(inputString, stringToBeSearchedInsideTheInputString).Length -1

End Function

Solution 4

str="Thisissumlivinginsumgjhvgsum in the sum bcoz sum ot ih sum"
b= LCase(str)
array1=Split(b,"sum")
l=Ubound(array1)
msgbox l

the output gives u the no. of occurences of a string within another one.

Solution 5

You just have to change the input of the split function into a string array and then delare the StringSplitOptions.

Try out this line of code:

Occurrences = input.Split({phrase}, StringSplitOptions.None).Length

I haven't checked this, but I'm thinking you'll also have to account for the fact that occurrences would be too high due to the fact that you're splitting using your string and not actually counting how many times it is in the string, so I think Occurrences = Occurrences - 1

Hope this helps

Share:
67,087
Matt
Author by

Matt

I am a proficient computer user, fairly good VB.NET programmer, and accomplished computer network hacker/security analyst.

Updated on January 20, 2021

Comments

  • Matt
    Matt over 3 years

    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 "hello there". So far, this is the code I have:

    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 = 0
    
    If input.toLower.Contains(phrase) = True Then
        Occurrences = input.Split(phrase).Length      
        'REM: Do stuff
    End If
    

    Unfortunately, what this line of code seems to do is split the string every time it sees the first letter of phrase, in this case, h. So instead of the result Occurrences = 2 that I would hope for, I actually get a much larger number. I know that counting the number of splits in a string is a horrible way to go about doing this, even if I did get the correct answer, so could someone please help me out and provide some assistance?

  • Matt
    Matt over 11 years
    This looks good, but can you add a little explanation as to what you're doing here?
  • NoAlias
    NoAlias over 11 years
    Thanks. Edited with a description.
  • jcansell
    jcansell about 9 years
    not sure why this is 'best answer' - Neolisk's string replace method below is much clearer… try it ! Print Len("Cat/Dogo/Rabbit") - Len(Replace("Cat/dog/Rabbit", "/", ""))-1
  • NoAlias
    NoAlias about 9 years
    Accepted answer doesn't always mean best answer.
  • DWRoelands
    DWRoelands over 8 years
    This is a lot of code for a task with a simpler solution. The "string/split/length minus one" method is easier to read and understand.
  • roland
    roland over 8 years
    How does this handle overlapping search strings? Dim inputString = "songs ABBABBA popsongs"' and 'Dim stringToBeSearchedInsideTheInputString = "ABBA" What would be the returned value (1 or 2)?
  • Gaucho
    Gaucho over 8 years
    interesting observation. The occourence of ABBA is 1 with my solution. If you need to handle such exception you need different approach, but i never needed it. Note: even the accepted solution doesn't fit your needs.
  • cssyphus
    cssyphus almost 6 years
    +1 Great answer - upvote it. Here it is slightly modified to be a one-line function.