i need to count the no of instances of a word in a string using vb.net
i can do the usual way as my problem is a little different

for eg i need to count the no of occurrences of -> in


tree_ptr->sub.another->valu=3;

so what you have tried till now ?

i actually thought of splitting into words and then counting but i dont how to split the words

are you working on any code ?

i am working on something bigger,but this problem i have to start from the scratch

1) you can either split the whole string with the string in question.. then simply get the length of the result array
2) use indexOf, get the first index, then use indexOf again with a startIndex > than the first result of indexOf.. keep going until indexOf = 0.. place all in a loop and it should work

use something like this:

Public Function findString(ByVal strData As String, ByVal strWhatToFind As Char) As Integer

        Dim cnt As Integer = 0
        For Each c As Char In strData
            If c = strWhatToFind Then
                cnt += 1
            End If
        Next

        Return cnt
    End Function

use:

Dim str As String = "tree_ptr->sub.another->valu=3;"
        Dim cnt As Integer = findString(str, "->")

value of cnt will be 2

Dim arTemp() As String = "tree_ptr->sub.another->valu=3;".Replace("->", "~").Split("~"c)
        MsgBox(arTemp.Length - 1)

Edited 5 Years Ago by codeorder: n/a

Dim arTemp() As String = "tree_ptr->sub.another->valu=3;".Replace("->", "~").Split("~"c)
MsgBox(arTemp.Length - 1)

nice logic.. :-O

This article has been dead for over six months. Start a new discussion instead.